Release notes#
Changelog#
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[Unreleased]#
[1.4.1] - 2026-11-15#
Changed#
mesh_optimalmerges neighbouring subintervals from a predicted merged error (new optionmerge_rule, default"predicted"). 1.3.0 and 1.4.0 merged a pair only when its summed error ratio was belowremove_cut / 2**(error_exponent - 1), which assumes the error estimate grows2**(k-1)-fold when two subintervals merge. On wide subintervals it grows far less (about2**8–2**9where2**20was assumed forgk21, measured in a warm-started PINN training loop), so safe merges were refused and warm-started calls kept more subintervals than they needed: that training loop used 24–74 % more integrand evaluations under 1.3.0 than under 1.2.2. The integrals themselves were as accurate.How it works. padaquad interpolates the integrand values already stored for the two neighbours onto the nodes the merged subinterval would have, and applies the method’s weights. That gives the merged subinterval’s integral and error estimate without evaluating the integrand. The pair merges when the larger of that error estimate and the difference from the sum of the two neighbours (the halves-versus-whole test of adaptive Simpson quadrature, Gander & Gautschi 2000), plus the neighbours’ own errors, is below
remove_cuttimes the tolerance. The difference term stops merges whose own error estimate would be blind, such as a kink that the merged nodes skip over. The prediction is linear in the stored values, so it uses weight vectors built once per ratio of neighbour widths and cached on the solver.Measured against 50-digit exact integrals (14 methods, 17 integrands, 2.57 million pairs, tolerances down to the rounding level):
pairs whose merge can cost accuracy: 86, against 12,058 for the 1.3.0 merge rule and 23,215 for the 1.2.2 one;
none of the 86 are on a Gauss–Kronrod or Clenshaw–Curtis method;
worst: 4.35 times the tolerance (1.3.0: 66);
safe merges actually made on the high-order methods: 99 % (1.3.0: 50–74 %).
Warm-start chains (306 chains, 6 warm calls each): 13.7 % fewer integrand evaluations; no starting subinterval had to be split again (1.3.0: 5); none ended less accurate than its cold start (1.3.0: 2).
Snapshots.
n_optimal_meshchanged in 90 of the 390 cases (86 smaller, 4 larger);integralandintegral_errorare unchanged in all of them.Cost. The weight vectors are built once per distinct ratio of neighbouring widths, about 2 µs each for
gk21and 20 µs forcc65on 8 CPU threads. Meshes grown from equal starting subintervals have few distinct ratios: 0.2–0.5 ms more per call on meshes of up to 64 subintervals, and on 10^6 equal subintervals buildingmesh_optimaltakes 0.40 s against 0.30 s (gk21) and 0.77 s against 0.38 s (cc65). A starting mesh of many random subintervals has one ratio per pair, and its warm-started meshes keep them: withN_init_steps=10**4and a cheap integrand, a cold call took 93 ms against 24 ms (gk21) and 245 ms against 27 ms (cc65), and a warm call 11 ms against 4 ms and 31 ms against 7 ms. For an integrand that is expensive to evaluate the difference is small in relative terms. The prediction works in chunks of pairs, so its temporary memory does not grow with the mesh (at most about 0.25 GB for gk21 and 0.7 GB for cc65). Open question:docs/issues/predicted-merge-cost.md.The older merge rules stay available as
merge_rule="power_law"(1.3.0 and 1.4.0) andmerge_rule="sum"(1.2.2). With a multi-coordinate integration variable (T > 1),"predicted"falls back to"power_law"with a warning.Limit, shared by every merge rule: a feature of the integrand that lies between the stored nodes cannot be seen.
Plan, evidence and its adversarial reviews: the commits of PR #69.
Fixed#
A node no longer lies past the end of its subinterval. Node i of a subinterval was placed at
left + c_i * (right - left); whenright - leftrounds (float32, wide subintervals) the last node came out one rounding step pastright, so it lay past the next subinterval’s first node and, on the last subinterval, outside the integration interval. Nodes are now placed withtorch.lerp, whose nodes at c = 0 and c = 1 are the mesh points bit for bit. The visible failure was anAssertionErrorin_merge_excess_nodes(node order after merging): the README’s gradient example, which runs in float32, failed for 37 of 2,000 random starting meshes withmerge_rule="predicted"and 1 of 1,000 on 1.4.0. Nodes with c ≥ 0.5 can move by a rounding step, so results can change at the rounding level.Building
mesh_optimalno longer takes time quadratic in the number of subintervals._rec_remove, which picks which of the flagged neighbouring pairs are merged, un-flagged about two entries per pass over the whole mask, so a call in which most pairs qualified for merging spent almost all its time there: 9.1 s of a 9.5 s call with 10^5 subintervals, for gk21, cc65 and dopri5 alike (about 15 minutes expected at 10^6). It now computes the same result in one pass (within each run of flagged pairs, keep every other one starting from the first): 0.07–0.10 s for the same calls. The output is unchanged, checked against the old loop on 2,580 random masks in the test suite, and the mask passed in is no longer modified. Details: PR #69.
[1.4.0] - 2026-11-15#
Removed#
The submodule
padaquad.integrate. It had the same name as the function it defined, sopadaquad.integratemeant the module or the function depending on how it was imported. Its code is now the private modulepadaquad._frontend.from padaquad import integrate, adaptive_quadratureis unchanged;from padaquad.integrate import integratenow raisesModuleNotFoundError; usefrom padaquad import integrate.max_path_change. The constructor argument and the early exit it controlled are gone;max_adaptive_splitsbounds refinement instead. Passingmax_path_change=now raisesTypeError. To migrate:To limit how much a call refines, set
max_adaptive_splits. The call returnsconverged=Falsewhen it stopped short of the tolerance, and repeatedsame_f=Truecalls refine further frommesh_optimal, which splits the failing steps (as the early exit’s stored mesh did; in cumulative mode a failing step can instead be merged with a right neighbour whose running integral, and so tolerance, is much larger).To see how much of the starting mesh failed, read
n_start_steps_split/percent_start_steps_split(below). Withmax_adaptive_splits=0nothing is split, so readconverged, or(result.error_ratios >= 1).float().mean(), the fraction of steps that failed when accepted (witherror_norm="failure_fraction",error_ratiosholds failure fractions, so compare with> mesh_failure_toleranceinstead).What is lost is the conditional behaviour “refine fully only when few starting steps fail”.
No positional constructor arguments.
max_path_changewas the 4th positional constructor argument. Every constructor option is now keyword-only (see Changed), so passing any of them by position raisesTypeError. Amax_adaptive_splitsthat is not an integer (intor numpy integer) raisesTypeError(a negative oneValueError), so a float meant formax_path_changecannot act as a cap.Support for Python 3.10. padaquad now requires Python 3.11 or newer (
requires-python = ">=3.11"), and CI tests Python 3.11 and 3.12. numpy 2.2.6 is the last numpy release that installs on Python 3.10, and its type stubs givenp.ndarrayno default type arguments, so the CI type check (disallow_any_generics) failed on it. The numpy used in CI (tests/requirements.txt) moves from 2.2.6 to 2.4.6, the newest release that supports Python 3.11._get_num_tableau_c()on both solvers. It recomputedsolver.C; usesolver.C.padaquad.runge_kutta(its contents moved as described under Changed),_VariableSubclass,_VARIABLE_SECOND_ORDER,_Interpolatory3Variable(useVARIABLE_METHODS["interpolatory3_variable"]) with itsb_delta,_b0,_ba,_b1andtableau_b(now the instance’sweight_function),n_tableau_c(usemethod.n_nodes),_get_tableau_b(usesolver.method.weights(nodes)),_Tableau.clone(useMethodClass.clone), and the solver attributesorder(never read; usesolver.method.order) andCm1(usesolver.C - 1)._sort_evals_into_meshand_sort_evals_into_mesh_full_nodes, which nothing called.
Added#
limit_benchmark_time(solver option, default True). The memory benchmark raises an error when it cannot measure the memory offwithin 60 s;limit_benchmark_time=Falseremoves that limit, for an integrand so slow that the measurement needs longer (for example a model of 5 s per call using 1 KiB per point, whose readings reach the 4 MiB noise floor only after 12 doublings of N, at N = 4096, and allow a fit two doublings later: 15 calls, 75 s). The time-limit errors name the option.padaquad.integrateaccepts it too.Split statistics on
IntegrationResult.n_start_steps(steps in the starting mesh: the caller’smesh, the mesh stored bysame_f=True, or a fresh one),n_start_steps_split(starting steps split at least once, including splits by the re-check of accepted steps), the propertypercent_start_steps_split(100 * n_start_steps_split / n_start_steps), andmax_split_depth(the largest number of times any one step was halved). They are read off the per-step split counter, which is now always kept (it was kept only when a cap was set); results are unchanged. Splits made afterwards to buildmesh_optimalare not counted. All three areNonein the per-batch result passed toloss_fxn.Type checking is enforced in CI, and padaquad ships its types.
mypy padaquad/runs in thetestsworkflow (both Python versions) with every function annotated and every function body checked (disallow_untyped_defs,check_untyped_defs,disallow_any_generics,no_implicit_optional; see[tool.mypy]inpyproject.toml). Before, about 37 functions had no annotations, so mypy skipped their bodies. The package now contains thepy.typedmarker (PEP 561) thatpyproject.tomlalready listed but that did not exist, so type checkers in projects that use padaquad see its annotations, andpadaquad/__init__.pydefines__all__.mypyis pinned to~=2.1.0in thedevextras so a new mypy release cannot fail CI on its own.MethodClass.measure_degree()measures a method’s polynomial degree from its tables. It integrates the Legendre polynomials P_k(2t - 1), k = 0 … 2C, over one subinterval with the method’s weights and with the lower-degree weights of its error estimate, and returns both measured degrees and the errors (DegreeMeasurement).UNIFORM_METHODS["gk21"].measure_degree()gives degree 31 and error-estimate degree 19. Legendre polynomials replace the powers t^k of the old exactness test: a method’s error on (2t − 1)^(d+1) is its Legendre error times (k!)² 2^k / (2k)!, which is 2.6e-17 for gk31 and below float64 rounding (for powers of t itself the factor is (k!)² / (2k)!, smaller still), so the power test reported degree 63 for gk31, 37 for cc33 and at least 130 for cc65.tests/test_exactness.pynow checks every method in both directions (exact through its degree, error at least 1e-8 one degree further; the smallest such error is 4.2e-6, for cc65), checks everyerror_exponent, and checks the stored tables in 60-digit arithmetic (mpmath, installed with torch through sympy).Verification scripts.
examples/verification/polynomial_degree.pymeasures every method’s degree and error-estimate degree;examples/verification/integral_accuracy.pyintegrates every function inintegrand_dictwith every method at tolerances 1e-6 and 1e-10 and checks each actual error against (number of subintervals) × tolerance. Both exit with status 1 when a check fails, and the test suite runs them.Documentation site. A Sphinx site (PyData theme) replaces the MkDocs template, which pointed at pages that did not exist: getting started, a user guide, an API reference generated from NumPy-style docstrings, the example scripts with their output, a Performance page, development notes, these release notes, a glossary and a bibliography (
docs/references.bib, holding only sources that were opened and checked). The methods table is generated fromUNIFORM_METHODSandVARIABLE_METHODS. The build (sphinx-build -W) fails on any warning.A benchmark against torchdiffeq that runs and measures fairly.
examples/speed_test/torchdiffeq_comparison.pyfailed on any machine without CUDA (device = "cuda"was hard-coded) and passed torchdiffeq an argument it does not have (mesh=). It now compares torchdiffeqdopri5, padaquaddopri5and padaquadgk21on six integrands with known integrals at two tolerances, recording median time over repeated runs, integrand evaluations, absolute error, hardware, versions and git commit, indocs/performance/results_<device>.json. On an Apple M2 Max CPU padaquad was 1.6 to 46 times faster at the same tolerance. The README’s “often two orders of magnitude faster” is replaced by these measured numbers; GPU runs have not been measured.MethodClass.references. Each method carries the keys ofdocs/references.bibfor the sources of its nodes and weights (a tuple of strings, validated); the documentation’s methods table cites them.Docstring checks. Every docstring in
padaquad/follows the NumPy format and passes numpydoc validation (all checks except See Also, Examples and extended summary; pre-commit hooknumpydoc-validation) and ruff’s pydocstyle rules.pytestalso runs the docstring examples (--doctest-modules), andtests/test_docs_vocabulary.pychecks the public docstrings and user pages for the documentation’s vocabulary rules.CITATION.cffwith the software’s citation metadata (checked against the Citation File Format 1.2.0 schema; a test keeps its version equal to the package’s).Development pages: how to add a quadrature method (with a worked Simpson’s-rule example) and how to publish the documentation.
Issue write-ups in
docs/issues/: the variable-sampling solver does not reuse evaluations on split, andintegral_erroris wrong after thetake_gradient=Falsere-check removes subintervals.
Changed#
f_unit_mem_sizeis replaced byf_mem_coeffs. The solver attribute set by the memory benchmark is now the fit (a, b, d), in GB, of the memory of one call on B points, a + b·B + d·B² (including the gradient factor and the reading’s error), instead of one cost per evaluation. Automatically chosen batches use 75 % of the usable memory (_MEMORY_BUDGET), so they are 25 % smaller than before for an integrand whose memory grows linearly. A memory benchmark that cannot measure the memory off(no reading reaches the noise floor, or the readings do not allow a fit within 60 s) now raises an error asking formax_batchinstead of choosing a batch of up to 1e9 points.scipyis imported only when the benchmark runs; the import adds about 0.3 s to the first benchmark in a process (measured on an Apple-silicon Mac, where the whole benchmark fortorch.sintook about 0.05 s before).convergedreports whether the returned integral meets the tolerance. It wasTrueon every call except amax_path_changeearly exit, including calls wheremax_adaptive_splitsleft steps failing. Every accepted step is now judged against the final integral (in cumulative mode, the final running integral through the step), the referencemesh_optimalis built with (also whenerror_integral_referenceis given), andconvergedisFalseif any fails or has a NaN/Inf error ratio. A step accepted at themax_adaptive_splitscap usually fails this check, but can pass it. A warning then reports the number and percentage of failing steps, the largest error ratio, and the failing steps’ summed error estimate next to the total over all finite steps and|integral|(for D > 1, all three for the output component with the largest relative failing error), followed by the remedies that apply to the call’s settings. Steps are accepted against the running integral, and withtake_gradient=True(the default) accepted steps are never re-checked, soconverged=Falsealso appears without a cap. Over 576 uncappedtake_gradient=Trueruns (bosh3, dopri5, gk7, gk21, cc9, cc17; six integrands on [0, 1], three of them cancelling; an rtol-dominated and an atol-dominated tolerance; two seeds; absolute and cumulative mode; the"2"and"failure_fraction"norms; eight steps per batch), 47 (8.2 %) returnedconverged=False, all in absolute mode, where the tolerance follows the running total; the median worst ratio of the"2"-norm failures was about 1e4, from cancelling integrands whose total is near 0. The same 576 runs withtake_gradient=Falseall converged. Integrals are unchanged; the result only reports what it did not report before.error_ratiosstill holds each step’s ratio at acceptance, so it can show every step passing whileconvergedisFalse.convergedisNonein the per-batch result.IntegrationResultis keyword-only and its fields are required. Fields typedtorch.Tensorused to default toNone. They are now required, and the dataclass accepts keyword arguments only, so a result built without one of them raisesTypeErrorinstead of carrying aNonethat fails later. Three fields can still beNone:mesh_optimal(in the per-batch result passed toloss_fxn, where no optimal mesh exists yet; always a tensor on a returned result),tracked_variables(when the integrand returns none), andloss(in the per-batch result beforeloss_fxnruns). The per-batch result now carriesy0as a zero tensor instead of the integer0. Code that builds anIntegrationResultitself must pass every required field by keyword.A missing integrand raises
ValueError.integrate()with nof, here or at construction, now raisesValueErrorfrom_check_variables; it was anAssertionError.max_batchis always a Pythonintinside the integration loop. When the memory budget exceeded the remaining work,max_batchbecame a 0-d tensor holding that count; it is nowmin(max_batch, int(remaining)), the same value. No change in results.One abstract
MethodClassfor every quadrature rule. The uniform rules (MethodClasswith a_Tableau) and the variable rules (_VariableSubclasswithtableau_b(c)) were two unrelated class families, and each solver carried its own copy of node placement, method setup, the integral computation and the weight lookup.MethodClassis now an abstract base declaringnode_fractions(),weights(nodes),to_dtype,to_device,n_nodesandclone(); Two generic classes implement it from data, and every registered rule is an instance of one of them:UniformMethodClassfrom a fixed_Tableau, andVariableMethodClassfrom node fractions and a module-levelweight_functionof the normalized node positions (interpolatory3_variableisVariableMethodClasswith_interpolatory3_weights). Both reject malformed node fractions (not 1-D, not from 0 to 1, or decreasing) withValueError, andVariableMethodClass.weightsrejects a weight function that does not return[N, C]. Node placement,_set_solver_dtypeand_calculate_integralnow exist once, inAdaptiveQuadrature. Consequences for code that uses these internals:MethodClass(order, error_exponent, tableau)can no longer be constructed; useUniformMethodClass.Both registries hold instances that
_get_methodclones per solver, soVARIABLE_METHODS[name]()no longer works;VARIABLE_METHODS["adaptive_heun"]is the same object asUNIFORM_METHODS["adaptive_heun"](its two nodes are the panel ends, so its weights cannot depend on positions).method.weights(nodes)returnsbandb_errorshaped[N, C, 1]for every rule (the uniform weights were[C, 1], adaptive heun’s[1, C, 1]); stored tables are[C], including adaptive heun’s, which was[1, 2].An unknown method name raises
ValueErrorlisting the valid names, from_get_method; it was anAssertionErrorin the solver or aKeyErrorin_get_method.UniformAdaptiveQuadratureandVariableAdaptiveQuadratureare defined inpadaquad.quadrature, andadaptive_quadraturein the private modulepadaquad._frontend(see Removed);from padaquad import ...is unchanged.
No numerical result changes: 1,280 integrations (both sampling modes, float32 and float64, gradients, D = 3, several batches,
conserve_memory, warm starts) give bit-identical tensors.The variable solver detaches its error estimates, as the uniform solver already did (they only drive accept/split decisions). With
take_gradient=Falseand a learnable integrand, itsintegral_errorandmesh_quadrature_errorsno longer require grad; the values are unchanged.The quadrature tables are built without numpy. Gauss-Kronrod tables are built with torch and Clenshaw-Curtis tables with Python floats and
math.cos(same summation order), so padaquad no longer imports numpy and every table is bit-identical to before.Both solver types build their method in one place. The variable solver built its method in
__init__with its own copy of_get_method’s steps; both solvers now build it in_set_solver_dtype, whichSolverBase.__init__calls when it sets the dtype (the uniform solver’s_setup_method, which only_set_solver_dtypeand__init__called, is merged into it).AdaptiveQuadrature.__init__no longer resetsmethod,order,CandCm1toNoneafter they were built, and the uniform solver no longer builds its method twice. A dtype change now rebuilds the variable method from its float64 definition rather than converting the existing one. No change in results: the variable methods’ coefficients (0, ±1/2, 1) are exact in float32 and float64.Tracked variables are stored as one record entry each (
tracked_variables_0,tracked_variables_1, …) instead of a list under one key, so every record value is a tensor and the record code has no special case for them. When the set of tracked variables differs between two recorded batches,_record_resultsnow raisesValueErrornaming both sets of record keys; before, tracked variables that first appeared in a later batch were dropped without a message, and tracked variables that disappeared raisedTypeError. An integrand that returns an empty tuple of tracked variables now getstracked_variables=None, the same as an integrand that returns none, in both the per-batch and the returned result; before, the returned result held(). No other change in results.SolverBase.integratedeclares the arguments every solver accepts, inAdaptiveQuadrature.integrate’s order (f, y0, mesh, mesh_init, mesh_final, then keyword-onlyf_args). It listedmesh_initandmesh_finalbeforemesh, the opposite of the only implementation._merge_excess_nodesis declared as an abstract method ofAdaptiveQuadraturewith its real signature (_compute_nodesis now one shared method; see theMethodClassentry above).Methods store their polynomial degree;
orderisdegree + 1.UniformMethodClass(degree, error_exponent, tableau)andVariableMethodClass(degree, error_exponent, c, weight_function)takedegree, the highest polynomial degree the method integrates exactly, in place oforder, which is now a read-only property returningdegree + 1(Gonnet 2012, ACM Comput. Surv. 44(4), Sec. 1 (arXiv:1003.4629v2, p. 3)). Both reject adegreethat is not an int ≥ 0 and anerror_exponentthat is not an int ≥ 2 withValueError. The degrees: adaptive_heun 1, fehlberg2 1, bosh3 2, dopri5 4; gk7 11, gk15 23, gk21 31, gk31 47; cc5 5, cc9 9, cc17 17, cc33 33, cc65 65; interpolatory3_variable 2 (3 with its middle node at the center).ordertherefore changes from 11/23/47 to 12/24/48 for gk7/gk15/gk31 and from 5…65 to 6…66 for cc5…cc65; the README and code comments that gave those methods a degree one too low are corrected. No algorithm readsorder; integrals are unchanged.The solver constructor is keyword-only and names every option.
AdaptiveQuadrature.__init__(inherited byUniformAdaptiveQuadratureandVariableAdaptiveQuadrature) now lists every option:f,method,atol,rtol,mesh_init,mesh_final,y0,remove_cut,max_batch,total_mem_usage,max_adaptive_splits,use_absolute_error_ratio,error_norm,mesh_failure_tolerance,error_on_nonfinite,dtype,device,output_speed_info, plus the multi-GPU options ofDistributedEnvironment. Before, the options were spread over three constructors joined by*args/**kwargs, and positional arguments filledremove_cut,max_batch, … in order. Passing any option by position now raisesTypeError; an unknown keyword raisesTypeErrornaming the solver class (it namedDistributedEnvironment.__init__).SolverBase.__init__takes its options as required keywords, so each default is defined once.remove_cut >= 1raisesValueError(it was anassert).adaptive_quadrature(sampling_type, method, **options).methodis now the second positional argument, as inintegrate(f, method, ...). Before,adaptive_quadrature("uniform", "dopri5")put"dopri5"intoremove_cutand failed withTypeError: '<' not supported between instances of 'str' and 'float'.padaquad.integrate(f, method, sampling, **options)accepts every solver option. Each keyword goes to the solver’sintegratecall if it is one of that call’s arguments, and to the constructor otherwise; the defaults are the solver’s (one source).f_args,same_f,N_init_steps,random_initial_mesh,loss_fxn,error_integral_referenceandconserve_memoryused to raiseTypeErrorbecause they were sent to the constructor. All options aftersamplingare keyword-only.samplingaccepts every nameadaptive_quadratureaccepts.method=None(the default of the constructor, the factory andintegrate()) means the sampling type’s default method, fromDEFAULT_METHODSinpadaquad/base.py:"gk21"for uniform sampling and"interpolatory3_variable"for variable sampling. Before, the one default"gk21"madeadaptive_quadrature("variable"),VariableAdaptiveQuadrature()andintegrate(f, sampling="variable")raiseValueError: Unknown method 'gk21'.Sampling-type names are case-insensitive in
get_sampling_type(and so inadaptive_quadrature), asintegrate(sampling=...)already was.
Fixed#
The memory benchmark no longer assumes memory grows linearly with the number of points. It called
fon N = 1, 10, 100, … points and made the next call whenever 10·M fit in usable memory (M the memory of the last call), then sized batches as usable memory ÷ (memory per point). For an integrand whose memory grows like N² (for example, per-point gradients withtorch.autograd.grad(..., is_grads_batched=True)), the next call needs about 100·M. popcornn reported that on its 16 GB CI runners the benchmark called N = 10,000 points (about 51 GiB) and Linux killed the process, which raises no catchable error; when the benchmark survived (only the 1 s limit stopped it), the batch, about 11,500 points, would have needed about 68 GiB (extrapolated from its readings). Now:Readings. A reading is never below the bytes of the call’s input and output tensors (alive when it is taken), so it is never 0. A reading counts as reliable when it reaches the reader’s noise floor: 10 KB on a GPU (whose counter is exact), 4 MiB on a CPU (smaller resident-memory readings are mostly noise: 0, or steps of 2 MiB). On Linux, glibc’s
malloc_trim(0)runs before each reading, so memoryftakes from memory the process freed earlier is counted (popcornn’s readings on Linux came out as low as 0 MiB where about 25 MiB was true; the trim recovered them). On macOS and Windows no such call exists (macOS’smalloc_zone_pressure_reliefreleased nothing in a test): there, in a process that has already evaluatedf, readings can be far too low, and the start warning says so and recommendsmax_batch. In 14integrate()calls in one process on an Apple-silicon Mac (a popcornn-like integrand using 266 bytes·N², 4 GB usable), 3 batches needed 0.65–0.97 times the usable memory, 6 needed 1.2–35 times it, and 5 calls raised; the benchmark’s own test calls needed more than the usable memory in 7 of the 14 (up to 6.9 times it). In an earlier run of the same kind, one batch was 1e9 points (three reliable readings that did not grow, so the fit was flat). Only the first call in the process gave a batch below the usable memory every time (0.76–0.86 times it, in three runs). On these readers the batch is now also capped at the largest test call, which ran (at least one subinterval’s nodes, the smallest batchtake_gradient=Truecan evaluate); for an integrand whose cost per point stops changing early this cap can be well below what fits (for 1 MiB + 1 KiB per point with 100 GB usable, 1e7 points where the fit allows 7.9e7). The benchmark’s own test calls are not bounded this way. The Linux error allowance E counts only the CPUs the process may run on (os.sched_getaffinity), twice, because a reading is the difference of two counts: 1 MiB on a 4-CPU machine, and 16 MiB instead of 512 MiB on a 256-CPU node pinned to 4 CPUs (1 GiB when the process may use all 256).The fit. Only reliable readings are fitted, as a + b·N + d·N² with a, b, d ≥ 0 (
scipy.optimize.nnls). The fit is ready when it uses three reliable readings and its memory grows by at least the noise floor from the first of them to the last; the search goes on until it is. Readings that grow less are within the noise, and readings that do not grow at all (a slow integrand with a fixed workspace, read in whole pages) gave a flat fit allowing 1e9 points. Before the fit is ready, each next call is sized by the worst case such a fit allows through the reliable reading with the largest N (or the latest reading, if none is reliable): y(k·N) ≤ k²·y(N).The next call is not 10·N but min(step·N, the largest N whose predicted memory fits in 75 % of the usable memory, the largest N predicted to take at most 1 s), with step 2 after a call that took more than 0.1 s on a reader that counts reused memory (a GPU, or Linux with
malloc_trim) and 10 otherwise. The time bound allows doubling N for the first two calls and while the fit is not ready (the 1 s limit is extended one doubling at a time). No call is started that is predicted to end past a total of 60 s for the whole measurement, the first two included (the time of the next call is predicted from a fit of the times, or as growing like N² before three calls; a call that takes longer than predicted cannot be interrupted, so the 60 s are checked again after it).Stops. The search stops, keeping the fit, when the cost per point changes by less than 1 % over each of the last two calls with the last three readings reliable and the fit ready (a reliable reading larger than these three, from memory
fallocated in that call only, can keep the fit from growing by the floor), when a call takes longer than 1 s (with the fit ready), at N = 1e9, when the next call would be less than 2·N, or when the measurement passes 60 s with the fit ready. It raises aRuntimeErrorthat explains what happened, lists every reading (N, MiB, seconds, and which were below the noise floor) and asks formax_batchwhen: a call uses more than 3 times the memory that growth like N² allows from an earlier reliable reading, M > 3·(N/N_i)²·(M_i + E), tested against the earlier reliable reading with the smallest bound (either the memory grows faster than N², which the fit cannot follow, or, on a CPU, the earlier reading missed reused memory: an integrand whose memory grows exactly like N² can then occasionally raise on macOS); the fit is not ready when the 60 s run out, or when the next call needed for it would fit in memory but is predicted not to finish in time (when it would not fit either, the memory budget ends the search; these errors namelimit_benchmark_time); or no reading is reliable when the search ends otherwise. When the memory budget (or an out-of-memory error, or N = 1e9) ends the search before the fit is ready, the batch uses the worst case N² through the reliable reading with the largest N, and the end message says so. In simulations of integrands growing like N or N² (16 B·N, 1 MiB + 1 KiB·N, 8 MiB + 64 B·N, 8 B·N², 0.25 MiB + 8 B·N²; 150 runs each, with 10× and with 2× steps), readings off by 0.5–1.5 times gave no false faster-than-N² error. Readings of 0 in 30 % of the calls (memory hidden from the reader, as on macOS in a process that has evaluatedf) gave false errors for 1 MiB + 1 KiB·N in 85 of 150 runs with 10× steps (125 with 2× steps, which only readers that see reused memory take) and for 8 MiB + 64 B·N in 19 of 150 with 2× steps, the same counts as before the comparison with every earlier reading: a reading of 0 is raised to the bytes of the input and output, which at a million points reaches the noise floor while being far below the true memory.The batch is the largest B whose fitted memory s·((a + E) + b·B + d·B²) fits in 75 % of the usable memory (s = 2.1 with
take_gradient=True, else 1). Run on the readings popcornn reported (memory 0.508 GiB and time 1.23 s at N = 1000, about 12.3 GiB usable,take_gradient=True) with fake memory and time, the benchmark of the first version of this change gave about 2,960 points (about 4.4 GiB forward, 9.3 GiB with the factor 2.1) instead of 11,500; popcornn itself was not rerun with this version.An out-of-memory error during the benchmark at N > 1 caps the batch at 0.75·N for the rest of the
integratecall (the cap the batch loop already uses after such an error) instead of estimating a cost from the free memory.After an out-of-memory error, the batch loop retries with 0.75 times the batch that failed. It took 0.75 times the cap
_oom_max_batchwhenever one was set, and the benchmark’s caps (above, and on macOS and Windows on every call) can be far above the batch: in a test with a cap of 1000 points, a 44-point batch that ran out of memory above 29 points was retried 11 times at 44 points before shrinking.The user guide lists the benchmark’s known limitations (“Limitations of the memory benchmark”, in Devices and memory), and the benchmark’s start warning links to that list, says the benchmark may underuse the hardware, and says that passing your own
max_batchavoids all of it, while reusing the benchmark’s result (solver.get_max_batch(),same_f=True) only saves its time.Limits: growth faster than N² that is not caught is underestimated: memory growing like N^p shows it only across a range of N over which (N/N_i)^(p−2) exceeds 3, so N³ is caught once two reliable readings are more than 3 times apart in N, and N^2.2 not before 243 times apart (comparing only with the previous reading, as before this change, let N³ pass after every 2× step); a large fixed cost delays this, because every bound includes it (in a simulation with 2× steps and 100 GB usable, 512 MiB + 10,000 bytes·N³ was not caught up to N = 128 and gave a batch needing 1.48 times the usable memory); an N² term too small to show in the reliable readings, or hidden by their noise, is missed when the cost per point looks constant; the before/after reader on macOS and Windows misses memory
ffrees before returning, and the CPU readers withoutmalloc_trim(macOS, Windows, musl, or a preloaded allocator such as jemalloc) miss memoryfreuses.
Test coverage reaches Codecov, measured on the installed package. Codecov showed 0% for two reasons:
Nothing was measured. CI installs padaquad non-editable, as users do, so the tests import the copy in
site-packages, whilesource = ["padaquad"]made coverage watch the./padaquadcheckout, which never ran (“No data was collected”).[tool.coverage.run]now measures the imported package (source_pkgs) and[tool.coverage.paths]reports it underpadaquad/. Runpytest --cov:--cov=padaquadrestores the old setting. The full suite measures 94%;fail_under = 90([tool.coverage.report]) fails a--covrun below that, so a run that measures nothing can no longer pass.Uploads went to the old repository name. Since the rename from
torchpathdiffeq(2026-05-30) the uploader sent reports tokhegazy/torchpathdiffeq, where they were discarded, and the step still passed. The upload (nowcodecov/codecov-action@v7) authenticates with GitHub’s OIDC identity of this repository, so no Codecov token is stored; a PR from a fork, which cannot get that identity, uploads without a token and does not fail its CI on a rejected upload.
The PyPI upload runs when a release is published.
.github/workflows/release.yamlran on thecreatedactivity, which GitHub does not send for a draft release (GitHub Docs, “Events that trigger workflows”,release), so a release saved as a draft and published later was never uploaded (the web interface may save a new release as a draft). It now runs onpublished, the activity the documentation workflow uses too.The re-check of accepted steps used the wrong running integral in cumulative mode. With
use_absolute_error_ratio=Falseandtake_gradient=False, each recorded step is re-judged against|running integral through it|; that sum was taken over the recorded steps only, leaving out the batch just evaluated, so steps to the right of a batch step were judged against the wrong value and could be left failing. It now uses the running integral of the record and the batch together. Cumulative-mode results can change; absolute-mode results do not.Known limitation documented:
fehlberg2’s error estimate ignores curvature. Its weights [1/512, 255/256, 1/512] and the lower-degree weights [1/256, 255/256, 0] make nearly the same error on a curved integrand (0.25098 and 0.24902 for t² on [0, 1], exact 1/3), so their difference, the error estimate, keeps only (f(end) − f(start)) / 512 times the width. Ondamped_sineat tolerance 1e-6, subintervals with estimates near 1e-7 have true errors near 1e-4, and the total error (1.0e-4) is larger than 84 subintervals × 1e-6. The behaviour is unchanged;examples/verification/integral_accuracy.pyreports it as[KNOWN]and the README warns about it.A failed constructor no longer prints a second error.
SolverBase.__del__calledend_processon a half-built object, so a constructor error was followed by an ignoredAttributeError: ... has no attribute 'is_distributed'.Two Gauss-Kronrod digits beyond float64 precision. gk21
wgk(3)differed from Netlib QUADPACK in its 33rd digit and the gk7 node 0.4342437… from its 28th significant digit; both now match an 80-digit computation. The float64 tables are unchanged.Descriptions corrected to match the code. The variable-sampling solver does not reuse integrand values when it splits a subinterval (
_evaluate_adaptive_nodesis not called byintegrate()), sointerpolatory3_variablealways has its middle node at the center, where it is Simpson’s rule; the README, docstrings and glossary said otherwise.adaptive_heun’s error weights subtract the right-endpoint rectangle rule, not Euler’s method (same size, opposite sign).integral_erroris approximate withtake_gradient=Falsewhen the re-check removes a subinterval (the absolute value of its estimate is subtracted from a signed sum). No behavior changed.
[1.3.0] - 2026-11-10#
Added#
adaptive_quadraturedefaults to uniform sampling.sampling_typewas a required argument, soadaptive_quadrature(method="gk21", ...), as written in the README’s warm-start example, raisedTypeError: missing 1 required positional argument: 'sampling_type'. It now defaults toDEFAULT_SAMPLING_TYPE("uniform", defined inpadaquad/base.py), the same constant that now sets the default of thepadaquad.integrate()wrapper’ssamplingargument, so both defaults change together.
Changed#
The memory benchmark now measures the memory cost of one integrand evaluation.
_setup_memory_checksmeasures one number, c (f_unit_mem_size), the memory one evaluation offuses; the batch size is still computed at every evaluation from live free memory (usable memory ÷ c). Before, nothing was measured: when a test call took longer than 0.1 s the code assumed 100·N points would fill memory, so c was about 100 times too small and batches about 100 times too large. The 1.2.2 entry below claimed the result “never extrapolates past the largest tile actually validated”; that was wrong. Now, for N = 1, 10, 100, … points, M (the memory one call used) is measured and c = s·(M + E)/N, with s = 2.1 fortake_gradient=True(a heuristic for backpropagation) and 1 otherwise:CUDA: peak allocated memory during the call minus allocated memory before it (
torch.cuda.reset_peak_memory_stats/max_memory_allocatedon the solver’s device). This counts memoryffrees before returning, such as the intermediates of a Jacobian computed insidef. It resets the device’s peak counters, includingmax_memory_reserved.CPU on Linux: the process’s peak resident memory (
VmHWMin/proc/self/status), reset before each call by writing5to/proc/self/clear_refs, which also resets the peak your owngetrusageor/usr/bin/timereport.ru_maxrssis not used because it also includes the peak of the process this one was started from, so in a worker started by a larger process (subprocess, multiprocessingspawn, a Jupyter kernel) it would read no memory use. The kernel’s per-CPU counters can read low by up to E = cores·max(32, 2·cores) pages (lib/percpu_counter.c), so E is added (1.5 MiB on 12 cores, 512 MiB on 256 cores).Other CPUs (macOS, Windows): resident memory after the call minus before. Memory
ffrees before returning is missed there.
The search stops when c changes by less than 1 % from N/10 to N, a call takes longer than 1 s, N reaches 1e9, or the next call is predicted not to fit (10·M > usable memory). After an out-of-memory error at N, the c measured at the previous N is kept if that N was at least 100; otherwise c = max(previous c, s·F/(0.75·N)), F the free memory before the call. The one-point check of
finintegrate()now runs before the benchmark, so one-time costs (CUDA start-up, lazy model loading) stay out of it. A single evaluation that does not fit raises a cleartorch.OutOfMemoryErrorinstead of tripping an internalassert; any other failure of the measurement stops the run with aRuntimeErrorsaying the memory could not be measured and thatmax_batchmust be passed, with the original error attached.integrate()now takes its dtype frommesh_finalwhen that is the only bound given.integrate()passedmesh_final=mesh_inittoset_dtype_by_input, so whenmeshandmesh_initwere bothNonethe dtype ofmesh_finalwas ignored and the integral ran in the solver’s construction dtype. A call that passes onlymesh_final(including through thepadaquad.integrate()wrapper) now follows the rule that already applied tomeshandmesh_init: the solver switches tomesh_final’s dtype. This can lower precision:mesh_final=torch.tensor([2.0])(float32 by default) on a float64 solver now integrates in float32. An integermesh_finalpassed on its own now raisesValueError: Given dtype must be torch.float64 or torch.float32; got torch.int64, as an integermesh_initalready did; pass a floating-point tensor.An unknown
sampling_typenow raisesValueErrorwith a message, instead of a bareKeyError.adaptive_quadrature('bogus')(andget_sampling_type('bogus')) raised a bareKeyError: 'bogus'; they now raiseValueErrornaming the bad value and listing the valid names. A sampling type that exists but is not adaptive (steps.FIXED,'fixed') or a value of the wrong type also raisesValueErrornaming it and the two supported types; previously that was aValueErrorwith no message. Code that caughtKeyErrorhere must catchValueError.padaquad now requires
torch>=2.4. The out-of-memory handling (_is_out_of_memoryand the batch-reduction re-raise) uses the top-leveltorch.OutOfMemoryError, which first exists in PyTorch 2.4.0 (release notes, #121702).pyproject.tomllistedtorchwith no lower bound, so on an older torch the first out-of-memory error would have become anAttributeError. 2.4 is the first version where that name exists, not a tested minimum: the code has been run on torch 2.8, and CI installs the latest release.The solver no longer changes process-wide PyTorch state. It used to call
torch.cuda.set_devicefor CUDA andtorch.set_default_devicefor CPU (andtorch.cuda.init), which affected all other code in the process. Only distributed runs still calltorch.cuda.set_device, which NCCL needs.solver.deviceis now always onetorch.device; a CUDA device always carries an explicit index.The memory benchmark’s messages. When it starts, a warning explains that
max_batchis being measured because adaptive refinement changes the evaluation batch at each step, that the measurement is slow and runs on everyintegrate()call withoutmax_batch, and how to skip it (passmax_batch, orsame_f=True). When it ends, a warning reports the time taken, why the search stopped, the bytes per evaluation, and themax_batchthe memory usable at that moment allows for the currenttake_gradient, to pass asmax_batchin later runs. Both are logged at WARNING level, so they are silent if your application configures logging above WARNING.The two split evaluation handlers share one batch loop.
_evaluate_f_on_split_nodesand_evaluate_f_on_split_residual_nodescarried byte-identical copies of the batchedfevaluation loop with its out-of-memory retry; both now call_evaluate_f_in_batches. The memory cleanup after an out-of-memory error or a memory benchmark is one method,_release_memory, which empties the CUDA cache only on a CUDA solver (previously it did so whenever any GPU was visible, even for a CPU solver). Dead commented-out code in the residual handler and inintegrate()was removed. No change in results.Memory management moved to
padaquad/quadrature/memory.py. The memory benchmark, the free-memory queries, the batch-size budget (get_max_batch,_get_max_f_evals) and_is_out_of_memorynow live in a_MemoryManagementmixin thatAdaptiveQuadratureinherits, so every method is still available on the solver. The benchmark is split into_setup_memory_checks(the search and its stop rules),_peak_memory_reader(how memory is measured on each device) and_measure_call(one test call), with comments explaining each step. No change in results.same_freplaces integrand matching byid(f). The solver used to rememberid(f)of the last converged call and, on a match, reuse the storedmax_batch(skipping the memory benchmark); ids are unreliable (a freed id is reused, and closures and bound methods get a new id on every call). The caller now says so withintegrate(..., same_f=True): the mesh andmax_batchstored by the last call that returned replace the caller’smesh/max_batch, and the benchmark is skipped. With nothing stored (first call) the caller’s values or the defaults are used. Both values are written together by every call that returns (converged, or stopped bymax_path_change, which now stores the mesh it stopped on with that batch’s failing steps split, and returns it asmesh_optimal, so the next call refines further instead of starting from, and stopping on, the same mesh) and never by a call that raises;previous_max_batchtherefore holds themax_batchof the last returning call, not of the last evaluation. Withoutsame_f=Trueormax_batch, the memory benchmark now runs on every call.max_path_changemeasures the whole starting mesh. It used the fraction of failing steps in each batch, so the two halves of one split step could end a call early, and a rough region in the first batch could end it even when the rest of the mesh passed. It now counts the failing steps of the starting mesh across all batches (split halves are not counted) against the starting step count, and stops as soon as that fraction reachesmax_path_change. It also runs on the stored mesh used bysame_f=True(reuse_mesh=Truenever ran it on the cached mesh), never on a freshly generated mesh.The mesh-merging cutoff accounts for how a step’s error grows when two steps merge.
mesh_optimalmerged a pair of steps when their summed error ratio S was belowremove_cut, without evaluating the merged step. A merged step of width 2h has an error of about 2^(k-1)·S when the method’s error estimate scales as h^k, so 7–22 % of those merged steps failed when the same integrand was re-evaluated onmesh_optimal(dopri5, gk7, cc17 in our tests). A pair now merges only when S <remove_cut/ 2^(k-1), so the merged step’s predicted ratio stays belowremove_cut; none failed in the same tests. Each method carries k aserror_exponent(2 for adaptive Heun and fehlberg2, 3 for bosh3, 5 for dopri5, 7/15/21/31 for gk7–gk31, 5/7/11/19/35 for cc5–cc65, and 3 forinterpolatory3_variable).mesh_optimalis larger in 150 of the 390 snapshot cases (up to 75 %, 8 → 14 barriers for cc17 ondamped_sineat the tight tolerance); integrals are unchanged, because merging happens only after convergence. For high-order methods at tight tolerances, or in float32, the error estimate is round-off, which does not shrink as h^k, so few pairs reach the cutoff: from a 512-step start on smooth integrands, 8 repeatedsame_f=Truecalls leave gk31 at 7–30 steps and cc65 at 74–264, where gk21 reaches 2–4.get_max_batch()defaults to the solver’stotal_mem_usageinstead of a second, fixed default of 0.9.
Removed#
integrate(reuse_mesh=...)and theprevious_f_idattribute. Usesame_f=True. Migration: withreuse_mesh=Truean explicitmeshwon over the cached one; withsame_f=Truethe stored mesh andmax_batchreplace the caller’s.same_ftakesreuse_mesh’s position, so a positionalreuse_meshargument now setssame_f.The
device_typeanddevice_idssolver attributes. Usesolver.device(atorch.device) instead.
Fixed#
Cumulative error mode merged steps that failed when re-evaluated. With
use_absolute_error_ratio=False, the summed error ratio of a pair of steps (used only to buildmesh_optimal) was divided by the tolerance of the larger of the two running integrals,max(|cum_i|, |cum_{i+1}|). The merged step ends where step i+1 ends, so it is judged against|cum_{i+1}|; where the running integral falls toward zero (e.g.cos(2πt)neart = 1), merged steps ofmesh_optimalhad error ratios up to 11 when re-evaluated. The pair now uses step i+1’s tolerance in both error-norm families. Absolute mode (the default) and all integrals are unchanged.The out-of-memory batch reduction crashed on the first out-of-memory error. The retry path in the split evaluation handlers computed
torch.int(torch.round(0.75 * self._oom_max_batch)):_oom_max_batchstarts asNone, so the first out-of-memory error raisedTypeErrorinstead of shrinking the batch, andtorch.intis a dtype, not a function. The batch is now seeded from the livemax_batchand shrunk withmax(1, min(round(0.75 * prev), prev - 1)), which strictly decreases (round(0.75 * 2) == 2would retry forever). This path had no tests;tests/test_oom_recovery.pynow covers it with a simulated out-of-memory integrand.CPU and CUDA-library out-of-memory errors are recognized. A refused CPU allocation raises a plain
RuntimeErrornamingDefaultCPUAllocator, numpy raisesMemoryError, a failedcudaMallocoutside PyTorch’s allocator raises “CUDA error: out of memory”, and CUDA libraries report their own allocation statuses (CUBLAS_STATUS_ALLOC_FAILEDand the cuSOLVER, cuSPARSE, cuFFT and cuDNN equivalents); none of these is atorch.OutOfMemoryError, so the batch loop and the benchmark crashed instead of shrinking the batch. They are now handled the same way. Any otherRuntimeErrorfromfstill propagates unchanged.Callers can choose the device, including the GPU index.
device="cuda:1"raisedValueErrorand atorch.deviceraisedAttributeError, so every solver ran oncuda:0(orcuda:<local_rank>when distributed).devicenow accepts"cpu","cuda","cuda:N", atorch.device, orNone(auto-detect), both on the solver and in thepadaquad.integrate()wrapper. One normalizer,_resolve_device, handlesdeviceandresult_deviceand raisesValueErrorfor an unsupported type, unavailable CUDA, a GPU index that is not visible, or (distributed only) an explicit index that differs from the rank’s GPU. Forresult_device, an index-less"cuda"means the solver’s GPU andNonekeeps results on the solver’s device.Cross-device crash in the accepted-panel re-check. When
result_devicediffered from the integration device, removing a re-split panel rebuilt the recordedlosson the integration device while new batches were recorded onresult_device, so the next recorded batch raised a cross-device addition error. The loss now stays on its own device.The integrand check call now passes
tshaped[1, T]for any number of time coordinatesT. Before integrating,integrate()callsfonce on the lower bound to check its output. That point was built withtorch.tensor([[mesh_init]]), which only works whenmesh_initholds one number (T = 1) and raisesValueError: only one element tensors can be converted to Python scalarsforT > 1. It is nowmesh_init.reshape(1, -1). No user could reach the old failure:T > 1is still stopped earlier by themesh_init < mesh_finalcheck in_setup_integral_bounds, soT > 1integration remains unsupported end to end. ForT = 1the shape ([1, 1]) is unchanged. The check call now receives the caller’s own bound tensor instead of a detached copy, so anfthat modifiestin place would change the caller’smesh_init; such anfalready fails inside the solver, which also passesfviews of its node array.
[1.2.2] - 2026-06-22#
Changed#
The per-evaluation memory benchmark (
_setup_memory_checks) was rewritten to be stable and self-limiting. It now grows the probe batch by powers of ten until the integrand either takes measurably long (eval_time > 0.1s), overshoots available memory, or reaches the1e9search ceiling, and derivesf_unit_mem_sizefrom the usable-memory budget at that point. The result is floored so the impliedmax_batchnever extrapolates past the largest tile actually validated — previously the time-based branch could imply amax_batch~100× the tested size and risk an out-of-memory error on the first real batch. On an out-of-memory event during the probe the batch is backed off (0.75 * N) and retried instead of aborting, and the benchmark now honors the caller’stotal_mem_usagefraction. It logs a warning when it runs (it is slow if repeated) and reports the resolvedmax_batchon completion.
Added#
get_max_batch(total_mem_usage=0.9, default_max_batch=None)on the solver: resolves the per-batch evaluation cap without re-benchmarking memory. Precedence is an explicitdefault_max_batch(e.g. a per-callmax_batch), then the construction-timeinit_max_batch, then the budget implied by a prior memory benchmark (f_unit_mem_size), all clamped by any_oom_max_batchdiscovered after an out-of-memory event. This lets calling code capturemax_batchafter a first run and feed it back into later solvers/calls to skip the slow benchmark.
[1.2.1] - 2026-06-16#
Changed#
Accepted integration panels are now re-validated against the drifting error tolerance. In absolute-error mode the accept/reject denominator (
max(atol, rtol * |I|)) depends on the running integral, which changes as more panels are evaluated — so a panel accepted early could later violate the current tolerance yet remain accepted, silently breaking the error guarantee. Each iteration the solver now re-checks every already-accepted (recorded) panel against the samereference_integralthe current batch uses; any that now fail are removed from the record and bisected in the same mesh update (_adaptively_increase_meshgained an internalextra_split_idxsargument), and their refined children are re-evaluated. At convergence every recorded panel satisfies the final tolerance. Runs only on thetake_gradient=Falsepath (where no per-batch backward can be double-counted and the full-integral denominator is available) and is skipped when a fixederror_integral_referencepins the denominator. Thetake_gradient=Truepath is unchanged. This can change the converged mesh and integral for multi-batch, drifting-denominator integrands (notably cancelling ones, where the denominator collapses towardatolas the integral cancels).Snapshot golden values are keyed per
take_gradientmode and regenerated. The two modes legitimately diverge once the re-check engages (they only ever coincided when every panel fit in a single batch);take_gradient=Truevalues are unchanged.
Fixed#
Default-loss detection in the record bookkeeping compared bound methods by identity (
loss_fxn is self._integral_loss), butobj.m is obj.misFalsefor bound methods, so the recordedlosswas never rebuilt after a panel removal. It now compares the underlying function; a customloss_fxnis still left as-is._rec_removerecursion overflow. The post-convergence prune helper was tail-recursive and hit Python’s recursion limit on the large, finely-refined meshes the re-check produces for cancelling integrands at tightatol. Converted to an equivalentwhileloop — identical output (snapshots unaffected), no depth limit.
[1.2.0] - 2026-06-14#
Changed#
Error tolerance is now computed against the complete integral (notable for memory-heavy integrands). The
take_gradient=Falseevaluation path (_evaluate_f_on_split_nodes) now evaluates every pending panel in a single pass before any accept/reject decision, so the integral is complete the first time a panel is judged. The absolute-mode tolerance denominator (max(atol, rtol * |I|)) therefore uses the full integral from the start, instead of the running (incomplete) integral that accumulated batch by batch. This yields better mesh-split decisions, but can change integration results for integrals large enough to span multiple batches (total_nodes > max_batch): the early panels are now judged against the true total rather than a too-small partial sum, so the converged mesh and integral can differ from prior versions. Small integrals that fit in one batch are unaffected.max_batchcontinues to bound memory by chunking thefcalls; it no longer fragments the error decision.
Added#
conserve_memoryargument onintegrate()(and the publicintegrate()wrapper), defaultFalse. WhenTrue, the solver uses the previous memory-conserving path (_evaluate_f_on_split_residual_nodes): it evaluates a bounded number of panels per loop iteration and carries a partial-panel residual forward across iterations, so peak memory is bounded bymax_batchrather than by the whole mesh. This restores the pre-1.2.0 incremental behavior (and the running-integral error denominator it implies). Use it when the full set of node evaluations does not fit in memory.
Fixed#
Bug:
_evaluate_f_on_split_nodesiterated an undefinedtracked_list(instead oftracked_lists) when concatenating tracked variables across batches, raisingNameErrorwhenever an integrand emitted tracked variables on the default path.
[1.1.1] - 2026-06-13#
Added#
result_deviceargument onintegrate()(and the publicintegrate()wrapper), default'cpu': the large per-step records (nodes,y,h,mesh_quadrature_errors,error_ratios,integral_error,loss,tracked_variables) are detached and moved toresult_deviceas they are recorded, so they no longer accumulate on the integration device. This bounds GPU memory on fine meshes — previously the full record grew on the GPU for the entire run even though most fields are only needed in the returned result. The two fields read back inside the loop (integralandmesh_quadratures) stay on the integration device. Whentake_gradient=Falsethe autograd graph is retained across the device move, so the returned integral remains differentiable (gradients flow back to parameters on the integration device).
Changed#
Record ordering is now by mesh position (robust to vector-valued time). Recorded panels are merged/sorted by each panel’s position in the mesh (its left barrier looked up in a
mesh_indicesmap) instead of by the first node’s first time-coordinate. The previous coordinate-0 key is not a valid total order whentis a vector (T > 1, e.g. path integrals) and could misorder the record; the mesh order is correct for anyT. For scalar time (T == 1) the order is unchanged and results are byte-identical (snapshots unaffected).Default result device (notable for CUDA users): with
result_devicedefaulting to'cpu',integrate()now returns the large result tensors on CPU by default; passresult_device='cuda'(or your device) to keep them on the GPU. The “mesh family” (mesh_optimal,mesh_init,mesh_final) always stays on the integration device becausemesh_optimalis the warm-start mesh fed back into the solver and its endpoints aremesh_init/mesh_final. On a CPU-only solverresult_deviceis a no-op.Device-consistent internals: the error-ratio helpers and adaptive-mesh refinement (
_adaptively_increase_mesh,_get_optimal_mesh) are now device-following (tolerances and allocations follow their inputs), and the merge/sort paths place index tensors on each field’s device, so a record split across devices stays consistent.Coordinate-0 assumptions removed for multi-dimensional
t: post-refinement/record monotonicity assertions are reframed (the 1-D strictly-ascending checks are retained, guarded toT == 1), initial sub-barriers are generated along the segment vector, and thereuse_meshwarm-start filter uses an all-coordinate bounding box instead of a coordinate-0 range.
Fixed#
The
max_path_changeearly-exitIntegrationResultis now device-consistent with the normal-completion path.
Removed#
Internal
_get_sorted_indices(coordinate-based binary-search merge), superseded by mesh-position placement (_mesh_order+_merge_positions).
[1.1.0] - 2026-06-09#
Added#
error_integral_referenceargument onintegrate(): in absolute-error mode the rtol denominator is the running (incomplete) integral, which over-refines early panels when the integrand’s mass is concentrated at later times. This argument accepts a Python float or tensor close to the true total, using it as the denominator from the first batch onward. Has no effect in cumulative mode.error_normargument (constructor + per-call override): pluggable vector-error norm schemes replacing the fixed RMS reduction, modeled onscipy.integrate.quad_vec’snorm:Norm family (
"2"default,"max","rms", or a callable) — reduce-then-compare: collapse the error vector with the named norm, compare to the tolerance."failure_fraction"— per-component control: each output element is compared against its own tolerance; a panel is accepted when the fraction of failing elements is ≤mesh_failure_tolerance(default0.0, requiring every element to pass).
Rounding floor (
max(tol, 50 * eps * |step|)): refinement halts at the working-dtype precision wall instead of refining indefinitely when the requested tolerance is below the dtype’s resolution.error_on_nonfiniteflag (defaultTrue): raises aValueErrornaming the offendingtwhenfreturns NaN/Inf, preventing silent wrong results.max_adaptive_splits: configurable ceiling on adaptive refinement depth (added in v1.0.2; documented here for completeness).
Changed#
Error tolerance formula (breaking for fine tolerances): the accept/reject threshold for the norm family has changed from
atol + rtol * |I|(additive) tomax(atol, rtol * |I|)(maximum), aligning withscipy.integrate. This tightens tolerance when both terms are comparable; snapshot values have been regenerated. Thefailure_fractionscheme retains the additive form.atolandrtolare now stored as dtype-aware tensors inSolverBaseand re-cast in_set_dtype.y0,mesh_init, andmesh_finaldefaults now honor the solver’s dtype rather than hard-coding float64.max_batch < C(take_gradient=False): sub-panel batch budgets are now supported. The split path processes one panel per iteration, evaluating itsCnodes across severalmax_batch-sized sub-batches and carrying remainders forward. The final integral is bit-identical to amax_batch ≥ Crun with the same seeded mesh.max_batch == 0at the dispatcher is rescued to1(with a warning); a direct unit call to_evaluate_f_on_split_nodesraisesAssertionError.take_gradient=TruebelowCcontinues to raise an error.Non-finite error ratios (from singular integrands) are routed into the accept mask rather than hanging the refinement loop indefinitely.
GPU device handling: user-provided meshes,
f_argstensors, and internal assertions are now consistently placed onself.device, fixing 850 test failures on CUDA machines.max_batchis cached between calls whenfis the same function, avoiding a full re-benchmark on everyintegrate()call.Out-of-memory errors during integration and memory benchmarking are caught;
max_batchis lowered and the evaluation retried.
Fixed#
Bug: the integral loss was computed as
sum(step²)instead of(integral)².Bug: misplaced parenthesis in the tolerance expression.
Bug:
VariableAdaptiveQuadraturedid not callmethod.to_device(self.device)at construction, leaving method tensors on CPU when the solver was on CUDA.Bug:
_merge_excess_nodesusednp.allclosefor a device-agnostic sanity check, which fails on CUDA tensors; replaced withtorch.allclose.Bug: non-finite error ratios caused an infinite adaptive refinement loop.
Removed#
error_calc_idxargument (superseded by the callable form oferror_norm).
[1.0.2] - 2026-05-30#
Added#
max_adaptive_splits: a configurable ceiling on adaptive refinement depth. Each panel tracks how many times it has been split (children of a depth-Npanel are depthN+1); once a panel reachesmax_adaptive_splitsit is accepted even if it still fails the error tolerance, instead of being split further. Defaults toNone(uncapped). Can be set at solver construction or passed to the integration call, with the per-call value taking priority. Applies to both uniform and variable sampling.
Changed#
Capped panels retain their failing
error_ratios(>= 1) in the result, so regions that hit the depth cap are visible; the run still completes normally.
[1.0.1] - 2026-05-30#
Added#
Tracked variables: the integrand
fmay now return a 2-tuple(integrand, tracked_variables)to emit extra per-node quantities that are evaluated at every quadrature node but not integrated. They are carried through the adaptive loop and returned at the accepted nodes in the newIntegrationResult.tracked_variablesfield, a tuple of tensors each shaped[N, C, *var_dims]and aligned withnodes/y. Values are detached (diagnostic-only). Works across both sampling modes, bothtake_gradientpaths, andfloat32/float64, and supports non-float (e.g. integer/boolean) tracked tensors.
Changed#
IntegrationResultgained the optionaltracked_variablesfield (defaults toNone).The sorted-insert step of the record is now dtype/device-aware, enabling non-float tracked variables to be recorded and sorted alongside the integrand evaluations.
Compatibility#
Fully backward compatible and opt-in: an integrand returning a bare tensor behaves exactly as before, with
result.tracked_variables = None. A single tracked tensor is wrapped into a 1-tuple, and(integrand, None)is accepted.
[1.0.0] - 2026-05-30#
First stable release. The project, formerly torchpathdiffeq (an ODE / path-integral library), has been rebuilt and renamed to padaquad, a PyTorch library for parallelized adaptive numerical quadrature: it computes definite integrals \(\int_a^b f(t)\,dt\) for a known integrand f by evaluating many quadrature panels in parallel batches on GPU/CPU, with full autograd through the integration loop.
The integrand f depends only on t (and optional extra args), not on accumulated state y. This is numerical quadrature, not ODE solving — for state-coupled \(\dot y = f(t, y)\) use torchdiffeq / torchode / diffrax.
Added#
Parallel, memory-aware batched evaluation: quadrature panels are evaluated in batches sized automatically to the available GPU/CPU memory budget.
Adaptive mesh refinement: panels that miss tolerance are split at their midpoint and re-evaluated; over-resolved regions are merged. The converged mesh can be cached and warm-started (
reuse_mesh=True) for repeated calls on the same integrand.Method portfolio (default
gk21):Gauss–Kronrod:
gk7,gk15,gk21,gk31Clenshaw–Curtis:
cc5,cc9,cc17,cc33,cc65Runge–Kutta baselines:
adaptive_heun,fehlberg2,bosh3,dopri5Variable-sampling rules:
adaptive_heun,interpolatory3_variable
Uniform and variable sampling modes (fixed tableau-
cnode positions, or arbitrary node positions with weights computed dynamically).Full autograd through integration, including a memory-frugal per-batch-backward mode (
take_gradient) for training learnable integrands whose full graph would not fit in memory.y0additive offset (result.integral = y0 + ∫f) and positionalf_argsforwarding tof(t, *f_args).Public API:
integrate,adaptive_quadrature,UniformAdaptiveQuadrature,VariableAdaptiveQuadrature,IntegrationResult,UNIFORM_METHODS,VARIABLE_METHODS,integrand_dict,wolf_schlegel,steps.
Changed#
Renamed package
torchpathdiffeq→padaquad. Update imports accordingly (from padaquad import ...).Reframed the public API around quadrature:
IntegrationResultexposes integral- and mesh-oriented fields (integral,integral_error,nodes,mesh_optimal,mesh_init,mesh_final,mesh_quadratures,mesh_quadrature_errors,error_ratios, …).float64andfloat32are the supported runtime dtypes;float16is refused at construction.
Removed#
ODE-centric framing and semantics.
padaquaddoes not integrate state-coupled ODEs; use a dedicated ODE library for those.
[0.0.2]#
Added#
Added
.pre-commit-config.yaml
Changed#
Use
rufffor formatting
[0.0.1]#
Added#
The initial release!