Skip to content

perf: replace numpy with pure Python arithmetic in miller - #172

Draft
ormsbee wants to merge 1 commit into
masterfrom
ormsbee/miller-drop-numpy
Draft

ormsbee wants to merge 1 commit into
masterfrom
ormsbee/miller-drop-numpy

Conversation

@ormsbee

@ormsbee ormsbee commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Closes #171.

Summary

miller.py was the only module in chem that imported numpy. It used it for arithmetic on 3D vectors when grading crystallography problems. This writes that arithmetic out in pure Python, and drops numpy as a dependency.

The reason is in #171: the long-term goal is to run LMS and Studio web processes without numpy, to reduce the memory they need. openedx-platform still gets numpy from other packages, so this doesn't save that memory by itself.

Which arithmetic

numpy didn't compute the same Miller indices on every CPU. np.dot calls OpenBLAS, which picks a kernel to suit the CPU:

  • Fused: the SkylakeX and Cooperlake kernels, for CPUs with AVX-512, add the terms of a 3D dot product with fused multiply-add.
  • Plain: the Haswell, Zen and Sandybridge kernels multiply and add each term separately, which rounds differently.

miller() tests dot products for exact zeros, so the two graded some answers differently. #171 has the details and a way to reproduce it.

miller() now does the same thing on every CPU. This is option 5 in #171:

  1. It computes the indices with fused arithmetic. Every answer that got Miller indices on a host with AVX-512 gets the same ones.
  2. If that raises ZeroDivisionError, it computes them again with plain arithmetic. Fused arithmetic is worse at noticing that a plane goes through the origin, and when it doesn't notice, sub_miller() divides by zero.
try:
    return _miller(points, _dot_fused)
except ZeroDivisionError:
    pass
return _miller(points, _dot_plain)

_miller is the old body of miller(), with the dot product passed in. The algorithm itself, the rounding of coordinates in grade(), and sub_miller are unchanged.

_dot_fused needs a fused multiply-add, and math.fma doesn't fit:

  • It needs Python 3.13, and chem supports 3.12, as openedx-platform does.
  • It raises an exception where numpy returned inf or nan.

So _fma() works out the exact product and sum with fractions, and rounds once.

Behavior changes

These counts are from the differential test below, on 1,000,000 random answers:

Host Answers that change How they change
With AVX-512 2,236 All go from ZeroDivisionError to Miller indices.
Haswell, Zen or Sandybridge kernel 2,433 2,313 get different Miller indices. 120 go from ZeroDivisionError to Miller indices.
  • Hosts with AVX-512: no answer that got Miller indices gets different ones. 991 of the 2,236 get indices no larger than 10, like the (3,-4,-5) example in Remove numpy dependency #171.
  • Other x86-64 hosts: no answer starts raising an exception. Most of the 2,313 have an index larger than 10 before and after, which no problem is likely to use as its correct answer. Counting only results with indices no larger than 10:
    • 108 answers lose such a result.
    • 204 answers gain one.
    • 51 answers change from one to another.
  • ARM hosts: not tested, so I don't know what changes there. They now grade the same way as every other host.
  • Planes through the origin: ZeroDivisionError is now rarer than it was with either kind of kernel. Of 85,480 such planes with points on the cube's edges, the fused kernels raised it on 4,506, the plain kernels on 2,956, and this branch on 2,946.
  • Points without exactly three coordinates still raise ValueError, but the message is different. numpy raised it from np.cross or from array broadcasting. miller() now checks for it.
  • miller() takes any sequences as points, not only numpy arrays.
  • Time: grade() takes about 38 microseconds on the machine I tested on, up from about 22 with numpy. The fractions arithmetic is the reason: with plain arithmetic alone it took about 8.

Evidence

Differential test: I ran chem 2.0.1 and this branch's miller.py on 1,000,000 random answers of three points each, and compared the Miller indices grade() computed, or the exception it raised:

chem 2.0.1 run with Kernel Answers that differ
numpy 1.26.4, Python 3.12 Cooperlake (fused) 2,236
numpy 1.26.4, Python 3.12 SkylakeX (fused) 2,236
numpy 2.5.5, Python 3.13 SkylakeX (fused) 2,236
numpy 1.26.4, Python 3.12 Haswell (plain) 2,433
numpy 1.26.4, Python 3.12 Zen (plain) 2,433
numpy 1.26.4, Python 3.12 Sandybridge (plain) 2,433
numpy 2.5.5, Python 3.13 Haswell (plain) 2,433

I also checked the rule itself on each of the 1,000,000 answers. This branch always gave what chem 2.0.1 gave with a fused kernel, unless that was ZeroDivisionError. Then it gave what chem 2.0.1 gave with a plain kernel.

numpy 1.26.4 is the version openedx-platform pins. OpenBLAS chose Cooperlake by default with numpy 1.26.4 on the test machine, and SkylakeX with numpy 2.5.5. The other kernels were forced with OPENBLAS_CORETYPE. The answers were:

  • 500,000 with points on the cube's edges, at multiples of 0.05
  • 200,000 with points anywhere in the cube, at multiples of 0.05
  • 150,000 on the edges, and 150,000 anywhere in the cube, with coordinates to two decimal places, to exercise the rounding in grade()

_fma against math.fma: on Python 3.13, the two agreed on all 999,954 of 1,000,000 random inputs that math.fma didn't raise an exception for, including the sign of zero.

Baseline from chem 2.0.1: The differential test needs numpy, so it can't live in this repo. Instead, miller_baseline.json records what chem 2.0.1 computed for 1,483 answers, and test_miller_baseline.py checks the current code against it. This follows the pattern of chemcalc_baseline.json in #169.

  • 41 answers are hand-picked: textbook planes, planes through the origin, rounding, degenerate and out-of-range points, and malformed input.
  • 1,300 are random, 300 of them chosen to be planes through the origin.
  • 142 more come from searching another 40,000 random answers for ones that chem 2.0.1 computed differently with the two kinds of kernel. 169 of the 40,000 did.

With 8 of the first 1,341, that makes 150 answers that depended on the kernel. Each records both results, as fused and plain. They're checked in two classes:

  • TestMillerBaselineFused: 40 answers where the fused kernel's result wasn't ZeroDivisionError. The code must give the fused result.
  • TestMillerBaselineRetry: 110 answers where the fused kernel raised ZeroDivisionError. The code must give the plain kernel's indices.

generate_miller_baseline.py made the file. It runs chem 2.0.1 with both kinds of kernel, and checks which arithmetic each one really does before trusting it. It refuses to run unless it's importing chem 2.0.1. It produced the same file with numpy 1.26.4 on Python 3.12 and with numpy 2.5.5 on Python 3.13.

Mutation checks: To see what the tests catch, I made each of these changes in a scratch copy:

Change to miller.py TestCrystallographyMiller TestMillerBaseline …Fused …Retry
_dot_fused does plain arithmetic 4 tests fail passes 40 of 40 answers passes
_dot_fused takes its terms in reverse order 3 tests fail 5 of 1,333 answers 34 of 40 passes
_dot_fused uses math.sumprod 2 tests fail 3 of 1,333 7 of 40 passes
_dot_plain does fused arithmetic 4 tests fail passes passes 110 of 110 answers
_dot_plain adds its terms in reverse order 1 test fails 1 of 1,333 passes 2 of 110
_dot_plain uses math.sumprod 3 tests fail passes passes 109 of 110
_fma returns x * y + z 5 tests fail passes 40 of 40 passes
_fma calls math.fma 1 test fails 1 of 1,333 passes passes
miller() doesn't retry 1 test fails passes passes 110 of 110
miller() tries plain arithmetic first, then fused 2 tests fail passes 35 of 40 passes
miller() retries after any ArithmeticError 1 test fails passes 1 of 40 passes
One component of _cross is negated 24 tests fail 867 of 1,333 39 of 40 94 of 110
The sign fix after the origin shift is dropped 3 tests fail 405 of 1,333 1 of 40 101 of 110
The coordinate count check is removed 1 test fails 6 of 1,333 passes passes

Removing any one branch of _fma fails test_fma, and no other test.

Tests: tox passes, both py and quality, and the tests pass on Python 3.12 and 3.13. The 32 existing TestCrystallographyMiller tests pass unchanged. Seven new tests in test_all.py cover:

  • fused arithmetic going first, on a plane that the two kinds of kernel gave (1,1,1) and (10,10,10) for
  • the retry, on a plane through the origin that raised ZeroDivisionError on hosts with AVX-512
  • an OverflowError from fused arithmetic, which isn't retried
  • _dot_fused and _dot_plain, on inputs where they differ and math.sumprod matches neither
  • _fma, against results from math.fma and for inputs that math.fma raises on
  • points without three coordinates
  • miller() taking tuples and lists

Not in this PR

🤖 Generated with Claude Code

@codecov

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 97.91%. Comparing base (855a76d) to head (1fba852).

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #172      +/-   ##
==========================================
+ Coverage   97.08%   97.91%   +0.82%     
==========================================
  Files           4        4              
  Lines         309      335      +26     
  Branches       62       66       +4     
==========================================
+ Hits          300      328      +28     
+ Misses          4        3       -1     
+ Partials        5        4       -1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ormsbee
ormsbee force-pushed the ormsbee/miller-drop-numpy branch from baaf288 to 76c93ae Compare November 20, 2026 20:30
@ormsbee ormsbee changed the title perf: replace numpy with plain arithmetic in miller perf: replace numpy with pure Python arithmetic in miller Nov 20, 2026
Base automatically changed from ormsbee/chemcalc-drop-nltk to master November 21, 2026 01:15
miller.py was the only module that imported numpy. It used it for
arithmetic on 3D vectors, which is now written out in pure Python, so
chem no longer requires numpy. That's one step towards running LMS
and Studio web processes without numpy, to reduce the memory they
need.

numpy didn't compute the same Miller indices on every CPU. np.dot
calls OpenBLAS, which picks a kernel to suit the CPU. For a 3D
vector, the SkylakeX and Cooperlake kernels, for CPUs with AVX-512,
use fused multiply-add. The Haswell, Zen and Sandybridge kernels
multiply and add each term separately, which rounds differently.
miller() tests dot products for exact zeros, so the two graded some
answers differently.

The new code does the same thing on every CPU. It computes the
indices with fused arithmetic first, so every answer that got
indices on a CPU with AVX-512 still gets the same ones. If that
raises ZeroDivisionError, it tries again with plain arithmetic,
which is better at noticing that a plane goes through the origin.
See #171 for the alternatives.

math.fma needs Python 3.13, and raises an exception where numpy
returned inf or nan. So _fma() does the fused multiply-add with
fractions instead.

Behavior changes, from running the new code and chem 2.0.1 on
1,000,000 random answers:

* On hosts with AVX-512, 2,236 answers that raised
  ZeroDivisionError get Miller indices. Nothing else changes.
* On hosts that used the Haswell, Zen or Sandybridge kernels, 2,313
  answers get different indices, and 120 that raised
  ZeroDivisionError get indices. No answer starts raising.
* A point without exactly three coordinates still raises ValueError,
  but with a different message.
* miller() takes points as any sequences, not only numpy arrays.

Tests:

* miller_baseline.json records the Miller indices chem 2.0.1 computed
  for about 1,480 answers. test_miller_baseline checks the current
  code against it.
* 150 of those are answers that chem 2.0.1 computed differently with
  the two kinds of kernel. They record both results, and are checked
  separately.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@ormsbee
ormsbee force-pushed the ormsbee/miller-drop-numpy branch from 76c93ae to 1fba852 Compare November 23, 2026 03:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Remove numpy dependency

1 participant