Skip to content

refactor(csp-batch): the host-only blocks of the driver as routines (step 4, first part) - #134

Merged
elijahmathews merged 1 commit into
feat/hotpath-03-blend-helperfrom
feat/hotpath-04-driver-stages
Nov 19, 2026
Merged

elijahmathews merged 1 commit into
feat/hotpath-03-blend-helperfrom
feat/hotpath-04-driver-stages

Conversation

@elijahmathews

Copy link
Copy Markdown
Owner

Stack: the unification plan (doc/HOT_PATHS_PLAN.md), step 4 of 5, first part, after #133. Merge order: ..., #132, #133, this.

What changes

compute_csp_batch was 1037 lines. Four blocks of it were host-only code with a clear input and output; they are routines now (the driver is 867 lines):

  • batch_check_shapes: the sizes of the optional arguments against the batch (status 3, or 2 for redshifted colours without zred_mags), and the modes the optional arguments make (parts, grad, given_w).
  • batch_check_models: the values of the models this path does not support (status 2): a non-positive age without given weights, an invalid uvb/wgp, an SFH whose gradient is not covered, isochrone modifications or IMF limits that differ from the SSPs', several metallicities without per-metallicity operators; and zvar.
  • batch_imf_vectors: the IMF parameter vector of every model and the operators' work arrays (with the per-model limits of feat(csp-batch): IMF mass limits per model (hot paths 6) #126).
  • batch_chain_derivatives: the chain-rule factors of the reverse pass.

No device code moves. The device-steered stages (SFH weights, the nebular and attenuation calls, smoothing, photometry) are still inline: splitting them needs a workspace type for the packed arrays and the device mapping rules checked on the R9700; that is not in this PR. doc/HOT_PATHS_PLAN.md gets the status and the finding below.

A finding that changed the check

At the default flags, forward dumps of this change differ from the parent's for about 7% of the models of a batch, by 1e-16 relative (up to 7e-16 in a pixel; gradient dumps 1e-14 of their scale), though the diff of the driver is the call and the removed checks. Bisecting: the shape-check extraction alone causes it; an empty call in its place does not; -O1 or -fno-tree-vectorize removes it; the library calls _ZGVbN2v_exp, _log, _log10 and _pow (glibc's libmvec: nm -D libopensps.so | grep _ZGV). GCC vectorizes loops that call exp, log and pow with the vector routines, which differ from the scalar libm by about an ulp, and which loops vectorize depends on the code around them. It is not uninitialized memory (heap poisoning with MALLOC_PERTURB_, locals set to NaN: no change), not inlining (-fno-inline), not the thread count, not FMA (the build has no -march). So CPU numbers of the library depend on the layout of the code at the 1e-16 level, which matters for how refactors are checked: the plan now says to compare CPU builds with -fno-tree-vectorize. The device kernels have no libmvec; their dumps stayed bit-identical through every step.

Verification

  • With -fno-tree-vectorize (the parent and this tree built alike, FP64, OpenMP host threads; N = 300, the resident basis, metallicity, [alpha/Fe], the IMF per model with the modification factors, a closed-form field): forward dumps 6 of 6 and gradient dumps 6 of 6 bit for bit.
  • At the default flags: 45 forward dumps agree to 1e-14 (observed 7e-16); 45 gradient dumps to 1e-14 of their scale.
  • Host FP64 and FP32: unit suite (45, including the refusal cases that these checks implement), test_csp_batch, test_batch_equivalence, test_csp_batch_grad green. R9700 device tests pass. nvfortran 26.1: compiles for the A100.

🤖 Generated with Claude Code

https://claude.ai/code/session_01MXDRCs7ATQiqhT6RLPLXR5

…argument and model checks, IMF vectors, chain-rule factors (unification plan, step 4, first part)

batch_check_shapes, batch_check_models, batch_imf_vectors and batch_chain_derivatives take the blocks of compute_csp_batch that were host code with a clear input and output (1037 lines to 867). Bit-identical with -fno-tree-vectorize (forward and gradient dumps of the resident basis, metallicity, [alpha/Fe], the IMF per model and the modification factors); at the default flags about 7% of the models differ by 1e-16 relative because GCC's vectorization of exp/log/pow calls through glibc's libmvec depends on the code around the loop (documented in the plan).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MXDRCs7ATQiqhT6RLPLXR5
@elijahmathews
elijahmathews added this pull request to stack #114 November 19, 2026 02:48
@codecov

codecov Bot commented Nov 19, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 63.11475% with 45 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.98%. Comparing base (c5d9dad) to head (0f7760e).

Files with missing lines Patch % Lines
src/physics/opensps_csp_batch.f90 63.11% 13 Missing and 32 partials ⚠️

❌ Your patch check has failed because the patch coverage (63.11%) is below the target coverage (85.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@                       Coverage Diff                        @@
##           feat/hotpath-03-blend-helper     #134      +/-   ##
================================================================
- Coverage                         75.00%   74.98%   -0.02%     
================================================================
  Files                                51       51              
  Lines                             14441    14461      +20     
  Branches                           6067     6077      +10     
================================================================
+ Hits                              10831    10844      +13     
+ Misses                             1479     1478       -1     
- Partials                           2131     2139       +8     

☔ 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.

@elijahmathews
elijahmathews marked this pull request as ready for review November 19, 2026 16:55
@elijahmathews
elijahmathews merged commit 370f168 into main Nov 19, 2026
15 of 16 checks passed
@elijahmathews
elijahmathews deleted the feat/hotpath-04-driver-stages branch November 19, 2026 17:49
elijahmathews added a commit that referenced this pull request Nov 19, 2026
…tage as routines (step 4, second part) (#135)

Stack: the unification plan (`doc/HOT_PATHS_PLAN.md`), step 4 of 5,
second part, after #134. Merge order: ..., #133, #134, this.

## What changes

Two more stages leave `compute_csp_batch` (867 to 809 lines):

- `batch_model_indices`: the host loop that forms every model's setup:
the age index of its birth-cloud time (`it_tesc`), its star formation
rate at its age (`sfr`, if asked), whether it has dust emission and the
interpolation indices and weights of the dust emission grid, and of the
AGN template.
- `batch_sfh_weights`: the SFH-weights stage, which is device code: the
weights of every model over the ages, copied from the given matrix on
the host for few models, copied on the device, or computed on the device
with `sfh_weights_core` (one thread per model). The comments about why
the host form is a plain loop (LLVM's libomp crash at one thread, #87)
travel with it.

The stage routines take what they read as explicit-shape dummies (the
same arrangement as `ssp_source_scalars`), and the packed parameter
array as the other stage routines do (`pbuf`, the raw words with flang).
Conditionals 961 to 962: the `#if` that selects the declaration of
`pbuf` in the new routine; the baseline is raised by one in this change.

## Verification

- CPU, both trees built with `-fno-tree-vectorize` (see the finding of
#134 on libmvec): forward dumps 6 of 6 and gradient dumps 6 of 6 bit for
bit (the resident basis, metallicity, [alpha/Fe], the IMF per model with
the modification factors, a closed-form field).
- R9700 (FP32 kernels, ROCm container, both trees rebuilt from scratch,
`csp_batch.f90` in both compile logs): 45 forward dumps of the
free-parameter matrix, 0 differ bit for bit. This part moves a device
stage, so these are the check of it.
- Host FP64 and FP32 suites, the six R9700 device tests, and the
nvfortran 26.1 compile for the A100 pass. Not run on an NVIDIA GPU: this
PR moves a device kernel launch, so it joins the list for the ICDS
session.

## Where step 4 stands

The nebular and attenuation calls, smoothing, photometry and the reverse
pass (about 180 lines, the 30 arguments of `batch_backward`) are still
inline. They share many arrays (the packed `ipk`, `rpk`, `lpk`, `rout`
and the work arrays), so cutting them needs a workspace type and the
device mapping rules checked on the R9700 after each cut; I would do
that as its own PRs.

🤖 Generated with [Claude Code](https://claude.ai/code)

https://claude.ai/code/session_01MXDRCs7ATQiqhT6RLPLXR5

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
elijahmathews added a commit that referenced this pull request Nov 19, 2026
…n programmers (#136)

Stack: after #135. Merge order: ..., #134, #135, this. Documentation
only.

`doc/HOT_PATH_TOUR.md`: a map of the hot path for someone who knows
stellar populations and not necessarily Fortran. The route of a call
from the C API to `compute_csp_batch`; the steps of the routine in order
(checks, per-model setup, SFH weights, age sums, nebular emission, dust
attenuation, dust emission, IGM and AGN, smoothing, magnitudes, the
reverse pass) with the routine and the file of each; the three sources
of the SSPs and the K slabs; the age-sum kernel as a first thing to
read; a glossary of the Fortran and OpenMP constructs the code uses
(`real(WP)`/`real(KP)`, `intent`, assumed and explicit shape, pointers,
`!$omp` directives, the `#if` switch, `.inc` templates); and where to
look when a batch is refused, slow, or differs between builds.

Names are used instead of line numbers, so the tour does not go stale as
the code moves; every routine named in it was checked to exist.

🤖 Generated with [Claude Code](https://claude.ai/code)

https://claude.ai/code/session_01MXDRCs7ATQiqhT6RLPLXR5

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
elijahmathews added a commit that referenced this pull request Nov 19, 2026
…nes, and a stage index in the driver (step 4, third part) (#137)

Stack: the unification plan (`doc/HOT_PATHS_PLAN.md`), step 4 of 5,
third part, after #136 (the tour). Merge order: ..., #135, #136, this.

## What changes

- `batch_mass_cotangent`: the mass output's cotangent in the reverse
pass (the resident basis): `wbl(k, m)` gains `mass_bar(m)` times the
model's blend of the basis' surviving masses, and with per-model
metallicity and gradients the `logzsol` and `afe` rows gain the mass's
derivative with respect to `dz` and `da`.
- `batch_sfh_gradients`: the SFH parameters' gradients through the
weights' tangents (`sfh_weights_tangent`, FP64 on the host, one model
per thread).
- A stage index at the top of `compute_csp_batch`: a comment that lists
the stages (0 checks and plan, 1 setup, 2 SFH weights, 3 age sums, 4
nebular, 5 attenuation, 6 dust emission / IGM / AGN, 7 smoothing, 8
magnitudes, 9 the reverse pass) with the routine of each, so that
reading the driver gives the map that `doc/HOT_PATH_TOUR.md` explains in
plain terms.

The code of the driver is 759 lines (1037 at the start of step 4), 775
with the index. The plan (`doc/HOT_PATHS_PLAN.md`) gets the status.

## Verification

- CPU, both trees built with `-fno-tree-vectorize` (see #134): forward
dumps 6 of 6 and gradient dumps 6 of 6 bit for bit (the resident basis,
metallicity, [alpha/Fe], the IMF per model with the modification
factors, a closed-form field). The gradient dumps exercise both new
routines (the benchmark gives `mass_bar` and the SFH parameters' rows).
- R9700 (both trees rebuilt from scratch, `csp_batch.f90` in both
compile logs): 45 forward dumps, 0 differ bit for bit.
- Host FP64 and FP32 suites, the six R9700 device tests and the
nvfortran 26.1 compile pass.
- The stage index is a comment (checked: it builds).

🤖 Generated with [Claude Code](https://claude.ai/code)

https://claude.ai/code/session_01MXDRCs7ATQiqhT6RLPLXR5

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
elijahmathews added a commit that referenced this pull request Nov 19, 2026
…139)

Stack: after #138. Merge order: ..., #137, #138, this. A rename,
bit-identical.

## What changes

The flags of `compute_csp_batch` had names that did not say what they
mean (`imf` is "the SSPs come from the operators", not anything about
the IMF itself; `zw`, `zmode`, `naf`...). In `opensps_csp_batch.f90`
(the routines of the driver and the stage routines that receive them):

| Old | New | Meaning |
|---|---|---|
| `imf` | `use_operators` | the SSPs come from the operators (`ssp_ops`
given) |
| `zimf` | `operators_per_z` | one operator per metallicity of the
context |
| `zw` | `weights_over_z` | SSP weights over ages and metallicities
(`ssp_weights_z`) |
| `zmode` | `blend_z` | each model blends the resident bases at its own
`logzsol` |
| `naf` | `n_afe_planes` | [alpha/Fe] planes of the stack (1: none) |
| `zvar` | `z_varies` | the redshifts or `igm_factor` differ among the
models |
| `given_w` | `weights_given` | the SFH weights were supplied |
| `host_w` | `weights_on_host` | few models: the SFH weights computed on
the host |
| `host_m` | `sums_on_host` | few models: weights and per-model sums run
on the host |

223 occurrences; word-boundary replacement in this one file (checked:
the new names were unused, no keyword arguments or other modules use the
old names), 15 code lines and 9 comment blocks that grew past 132
columns reflowed (the comment blocks as whole paragraphs).
`doc/HOT_PATH_TOUR.md` gets a table of the flags and one of the driver's
main arrays (`weights`, `w2`, `yo`, `total`, `absorbed`, `tdiff`, `eml`,
`msum`..., the packed `ipk`/`rpk`/`lpk`/`rout` and the names that view
into them), and the plan the new names.

## Verification

- CPU, both trees built with `-fno-tree-vectorize` (see #134): forward
dumps 6 of 6 and gradient dumps 6 of 6 bit for bit.
- R9700 (both trees rebuilt from scratch, `csp_batch.f90` in both
compile logs): 45 forward dumps, 0 differ bit for bit.
- Host FP64 and FP32 suites, the six device tests and the nvfortran 26.1
compile pass.

🤖 Generated with [Claude Code](https://claude.ai/code)

https://claude.ai/code/session_01MXDRCs7ATQiqhT6RLPLXR5

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
elijahmathews added a commit that referenced this pull request Nov 19, 2026
…s of a batch (#140)

Stack: after #139. Merge order: ..., #138, #139, this. A move of
procedures within one file; no procedure changed.

## What changes

The procedures of `opensps_csp_batch.f90` were in the order in which
they were written, with the forward stages, their helpers and the
reverse pass interleaved. They now follow the stages of a batch, in the
order in which `compute_csp_batch` runs them:

- the driver, then stage 0 (checks and plan), 1 (per-model setup), 2
(SFH weights), 3 (age sums, mass and L_bol, the slab blend and kernels),
4 (nebular emission), 5 (dust attenuation), 6 (dust emission, IGM, AGN),
7 (smoothing), 8 (outputs), and 9 (the reverse pass, the largest
section),
- a banner for each, and a table of contents after `contains`, so that
the file reads as the hot path from top to bottom (search for `Stage 3:`
to jump to the age sums).

How it was done, and why it is safe: a small tool segmented the file
into 84 units (a procedure with its doc comment, any preprocessor
wrapper around it, and the `#define`/`#include`/`#undef` block after it,
for the template instances) and moved each whole. A mechanical check
showed that the new file holds exactly the lines of the old one plus the
45 banner and table-of-contents lines: nothing lost, nothing duplicated.

A split into several modules was considered and not done: the routines
call each other across the stages (the reverse pass reuses the forward
helpers; the types and constants are shared), so the pieces would need a
common module under them and a long chain of `use` lines, for little
more than the order already gives. `doc/HOT_PATH_TOUR.md` and
`doc/HOT_PATHS_PLAN.md` say so.

## Verification

- CPU, both trees built with `-fno-tree-vectorize` (see #134): forward
dumps 6 of 6 and gradient dumps 6 of 6 bit for bit.
- R9700 (both trees rebuilt from scratch, `csp_batch.f90` in both
compile logs): 45 forward dumps, 0 differ bit for bit.
- Host FP64 and FP32 suites, the six device tests and the nvfortran 26.1
compile pass.

🤖 Generated with [Claude Code](https://claude.ai/code)

https://claude.ai/code/session_01MXDRCs7ATQiqhT6RLPLXR5

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
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.

1 participant