Release Notes#
Version 0.3.0 (2026-06-19)#
This release completes the library-wide correctness audit campaign begun in
0.2.0. The two remaining major modules — cogtask and metric — received
their first dedicated static audits, while optim, trainer, visualize,
surrogate, and init underwent deeper second-pass re-audits whose findings
were each verified against reference implementations (optax 0.2.6,
torch.optim, PyTorch’s NAdam) and numeric reproductions. Every fix is locked
in behind a regression test suite. The changes are corrections to existing
behavior — no intentional API breaks — but the breadth and the genuine
numerical/algorithmic bugs corrected (double-applied SM3 momentum, a centered
RMSprop that was a silent no-op, dropped Parallel branches in cogtask,
distributed broadcast that failed on more than one device, and more) warrant
the minor-version bump.
Highlights#
Audit campaign completed:
cogtaskandmetricare now audited, and the five previously-audited modules were re-audited against their reference implementations, replacing plausible-but-unverified behavior with reference-checked correctness.Real algorithmic fixes: SM3 no longer applies momentum twice;
RMSprop(centered=True)actually centers;Nadamhonorsmomentum_decay;cogtask.Parallelno longer silently drops compound (>>/Repeat) branches; distributedbroadcast()works on more than one device.Restored public API:
cogtask.create_taskandmetric.L1Lossare now importable from their packages (both were documented but absent from__all__).Regression coverage: each audited module ships a dedicated regression test suite (
visualizeexercised source at 99%,surrogateat 100%).
Added#
braintools.cogtask.create_taskis now exported from the package (#122).braintools.metric.L1Lossis now exported (documented but previously missing from__all__) (#121).
Fixed#
braintools.optim (#120) — re-audit verified against optax 0.2.6 / torch.optim#
SM3 no longer applies first-moment momentum twice;
momentum=0now truly disables it (matchesoptax.sm3).RMSprop(centered=True)usesscale_by_stddevinstead of silently falling back toscale_by_rms.Nadamimplements PyTorch-style scheduled momentum somomentum_decaytakes effect (verified againsttorch.optim.NAdam).LBFGSreads the live LR schedule each step instead of freezing the LR at construction;CosineAnnealingWarmRestarts.step(epoch=...)recomputesT_cur/T_ifrom the absolute epoch.Fail-fast validation of optimizer hyperparameters and scheduler enums;
default_txuses coupled weight decay; several non-runnable docstring examples corrected.
braintools.trainer (#119)#
Metrics logged via
module.log()from callbacks/hooks (e.g.LearningRateMonitor) survive the JIT loss reset and now reach loggers and the progress bar.ModelCheckpoint(save_top_k=k)saves before pruning so evicted checkpoints are deleted and the on-disk count respectssave_top_k.Resuming a checkpoint saved with
step=Noneno longer crashes the loop.broadcast()reimplemented vialax.all_gather()[src](it raised on more than one device); FSDP auto-mesh uses a balanced 2-D factorization;sync_batch_normpools variance viaE[x²] − E[x]².
braintools.metric (#121)#
phase_locking_valueaccepts abrainunit.Quantitydt(including theenviron.get_dt()default) instead of crashing.pairwise_cosine_similarityfloors each row norm ateps(not the norm product), so small non-zero vectors are no longer corrupted.cross_correlationstrips units soQuantityinput works;lfp_phase_coherencesuppresses spurious coherence on negligible-power channels.voltage_fluctuationReturns docstring corrected;smooth_labelsraises a realTypeErroron bad dtype;victor_purpura_distancebuilds its DP table on host NumPy (functionally identical, far faster).
braintools.cogtask (#122)#
Parallel.executedispatches compound children throughexecute_phase, so e.g.(A >> B) | Cno longer silently writes nothing for theA >> Bbranch.make_encoder(mode="scalar", feature_per_direction>1)is handled up front instead of raising a misleadingUnknown mode=scalar.Runnable-example fixes across the
__init__quickstart and theTask,create_task,Feature.__mul__, andContextdocstrings.
braintools.visualize (#118)#
Edge-case robustness fixes across
line_plot,spike_raster,animate_1D/animate_2D,confusion_matrix,regression_plot,neural_trajectory,correlation_matrix,roc_curve,brain_surface_3d, andvolume_rendering— non-ndarrayinput, length mismatches, empty-row normalization, constant-yR², and signed/colormap handling no longer crash or produceNaN. Exercised source at 99% coverage.
braintools.surrogate (#117)#
LogTailedRelu.surrogate_funis now continuous and C¹ atx = 1(1 + log(x), per Cai et al. 2017); it previously jumped1.0 → 0.0. The surrogate gradient (1/x) is unchanged, so training behavior is unaffected. Docstring and plot examples corrected.
braintools.init (#115, #116)#
param()no longer double-applies the batch dimension for callable/Initializationinitializers (it returned(batch, batch, *sizes)).TruncatedNormalhandles array-valuedstd(including zero entries) without raising;param()consistently returns the updatedStateand validates shape against the State’s value. Documentation corrected forKaiming{Uniform,Normal}scale,Identity1-D behavior, and theOrthogonal/DeltaOrthogonaldeprecation warnings.
Version 0.2.0 (2026-06-18)#
This is a codebase-wide correctness, test-coverage, and documentation
release. Nearly every major module — metric, trainer, optim,
visualize, surrogate, quad, init, conn, and file — received a
dedicated static audit; the findings were resolved with fixes and locked in
behind comprehensive new test suites that raise per-module coverage to
roughly 92–100%. The audits uncovered and corrected genuine mathematical and
numerical bugs that had previously gone unnoticed — inverted surrogate-gradient
formulas, a sign error in nll_loss, coherence metrics that were identically
one, He-initialization variance off by a factor of two, and unit-handling
crashes in the ODE/SDE integrators under newer saiunit. Documentation was
realigned across the board so that docstring examples, notebooks, and the API
reference are runnable and accurate. Alongside the fixes, the release adds new
public API in file, trainer, optim, metric, and init, and modernizes
the CI and build configuration. The minor-version bump reflects the breadth of
behavioral corrections rather than any intentional break in compatibility.
Highlights#
Library-wide audit pass: every audited module ships corrected behavior plus a dedicated regression/correctness test suite, lifting coverage to ~92–100% and replacing previously self-referential tests with reference-value checks.
Real numerical-correctness fixes: corrected surrogate-gradient formulas (
GaussianGrad,Arctan,ERF,PiecewiseQuadratic, …), annll_losssign error, LFP coherence that was identically1, He/Kaiming initialization variance that was off by 2×, and integrator unit handling undersaiunit.New public API:
braintools.file.save_matfile, gradient accumulation and name-based parameter freezing inbraintools.trainer, a line-search API forLBFGSinbraintools.optim, and exportedsafe_norm/ pairwise-cosine helpers inbraintools.metric.Modernized infrastructure: Python 3.14 configuration,
codecov-actionv5 → v7, enforced LF line endings, and removal of the brokenscienceplotsintegration that was failing CI.
Added#
braintools.file#
save_matfile: save a dictionary to a MATLAB.matfile, the counterpart toload_matfile(#104).
braintools.trainer#
Gradient accumulation: accumulate gradients across micro-batches, numerically equal to a single full-batch step (#112).
Name-based parameter freezing: parameters selected by name are now genuinely frozen by the trainer (#112).
braintools.optim#
LBFGS.update(grads, value=, value_fn=): public line-search API supporting zoom and backtracking line searches (#111).
braintools.metric#
safe_normis now exported, along with the pairwise helperspairwise_cosine_similarityandpairwise_cosine_distance(built on a gradient-safe norm).huber_loss,log_cosh, andl2_lossgainaxisandreductionarguments (#108).
braintools.init#
VarianceScalingand theInitializeralias are now part of the public API, andExponentialProfilegains adecay_constantargument (#106).
Changed#
braintools.optim(#111):ChainedSchedulercombines factors multiplicatively, matching PyTorch;PiecewiseConstantScheduleis documented and treated as absolute LR values;ReduceLROnPlateau’s incompatibility withChainedScheduler/SequentialLRis documented.Multi-group
step()updates the default group through the maintxand each added group through its owntx, while parameters outside any added group still update.SciPy backend casts
x0/jac/boundsto float64 for the TNC/SLSQP Cython kernels and skipsjacfor gradient-free methods; the Nevergrad backend gains reproducible seeding and an all-NaN recommendation fallback.
braintools.visualize(#110):line_plot/raster_plotdraw onto the passedAxesrather than the pyplot state machine, so labels, limits, and titles land on the right subplot.animate_1D/animate_2Dfall back todt=1.0outside a brainstatedtcontext instead of raisingKeyError;static_varsaccepts arrays, lists, or labeled dicts.apply_stylevalidates the style name and returns a context manager that restoresrcParamson exit;brain_surface_3dusesplt.get_cmap(replacing theplt.cm.get_cmapremoved in Matplotlib 3.11).
braintools.init(#106):TruncatedNormaluses a jit-traceable, backend-agnostic inverse-CDF sampler (ndtr/ndtri) in place ofscipy.stats.truncnorm, andVarianceScalingcompensates for the truncated standard deviation so the achieved variance matches the target.Distance profiles use unit-aware math throughout; the per-call
unitargument on basic distributions is deprecated in favor of unit-bearing quantities.
braintools.conn(#105):Per-edge weights and delays are aligned to CSR row order in
weight2csr/delay2csr;__call__result caching is keyed on(pre_size, post_size, position ids)so changed sizes recompute, andScaledConnectivityno longer mutates the base connectivity’s cached result.Spatial/kernel connectivities gain autapse control via
allow_self_connections, andExponentialProfileadopts thedecay_constantAPI.
braintools.file(#104):The matfile reader replaces the deprecated
scipy.io.matlab.mio5_paramswith the publicmat_struct, detects MATLAB v7.3 (HDF5) files and raises an actionableNotImplementedError, and renames the invertedheader_infoflag toinclude_header(deprecated alias retained).msgpack_loadplumbsmax_sizethrough (None = unlimited, replacing the hard 10 GB cap) andmsgpack_savereturns its filename and writes via a unique temp file so concurrent saves no longer clobber each other.
braintools.trainer(#112): single forward pass per training step viagrad(..., has_aux);EarlyStoppingmin_deltakeyed offmodeand gated bymin_epochs; validation/test metrics prefixed via_prefixed()(eliminatingval_val_loss);seedseeds both NumPy and brainstate; honest validation and warnings forprecision,deterministic/benchmark, multiple optimizers, and distributed strategies.
Fixed#
braintools.surrogate(#109) — formula corrections, caught after the self-referential test suite was replaced with reference-value checks:GaussianGradexponent corrected to-x²/(2σ²)(the σ dependence was inverted);Arctan.surrogate_funrebuilt aroundarctan(it had misusedarctan2, leaving the range outside[0, 1]);ERF.surrogate_funcorrected to be increasing.PiecewiseQuadratic.surrogate_gradis now the continuous trianglea − a²|x|;PiecewiseLeakyRelucentral slope fixed to1/(2w);QPseudoSpike.surrogate_funrewritten as a finite antiderivative;SquarewaveFourierSeriesoff-by-one term count fixed.S2NN/LogTailedReluguard deadwhere-branch denominators to avoid NaN gradients.
braintools.metric(#108, #113):nll_losssign error fixed (with N-D support added); KL divergence made gradient-safe via the double-wherepattern;ctc_lossusesjax.randominstead of a nonexistentjnp.random.LFP fixes: corrected Welch PSD normalization, magnitude-squared coherence (which had been identically
1), Tort PAC, andcurrent_source_densityaxis/conductivity/units.lfp_phase_coherenceis vectorized and its PLV output is bounded to[0, 1]with an exactly-1diagonal, removing float32 roundoff that pushed values marginally above one (#113).firing_ratewidth/dt scaling corrected;spike_train_synchronymade symmetric;cross_correlation,voltage_fluctuation, and the loss reductions gained shape / zero-variance / zero-weight guards. The misspelled_pariwisemodule was renamed to_pairwise.
braintools.quad(#107) — all Butcher tableaux verified correct; bugs were concentrated in unit handling and noise sampling:ode_expeuler_step/sde_expeuler_stepdivide the diagonal Jacobian by the state unit sodt·Ais dimensionless (previously crashed undersaiunit >= 0.4);sde_expeuler_stepsamples the Brownian increment from the shape ofy;sde_euler_stepusesu.math.sqrt(dt)for unitfuldt.ode_dopri5_stepexploits the FSAL property to drop one redundant stage, computingk7only whenreturn_error=True.
braintools.init(#106):KaimingUniform/KaimingNormaluse the correct He variance (scale=2.0for ReLU,2/(1+slope²)for leaky ReLU; it had beensqrt(2), giving half the intended variance).param()restores theStatevalue into the returned parameter, and_to_sizerejects boolean sizes.braintools.conn(#102):CompositeConnectivity._unionuses explicitis not Nonechecks instead of array truthiness, fixing aValueError: truth value of an array ... is ambiguousthat broke CI.braintools.visualize(#110):remove_axis()with no spine names blanks the panel;firing_rate_maphandles non-squaregrid_sizeand edge points; Spearman correlation builds a 2×2 matrix for exactly two features; ~26 broken docstring examples were corrected.braintools.file(#104): checkpoint restore validates array shape and honorsmismatch(wrong-shaped arrays were silently loaded), dispatches to the most-specific registered subclass, and stops misfiring the namedtuple-envelope heuristic on genuine namedtuples;AsyncManagersurfaces background-save failures instead of swallowing them.
Infrastructure#
Dependencies: bumped
codecov/codecov-actionfrom v5 to v7 (#101).Python 3.14: project and tool configuration updated for Python 3.14.
Line endings: enforced LF via
.gitattributes, with binary rules for image/data assets andeolrules for.ps1/.sh; three CRLF-committed files were renormalized with no content change.scienceplotsremoval: the unused_style.pyscienceplots integration was removed — it depended on an undeclared package and on internal Matplotlib APIs removed in newer releases, which was breaking CI on Python 3.13 (#103).Audit reports: each module audit committed its findings under
docs/braintools-<module>-issues-found-20260618.md.
Version 0.1.10 (2026-06-09)#
This release adds two forward-mode second-order optimizers — SOFO and
SOFOScan — to braintools.optim, and hardens the braintools.cogtask
task engine so that conditional combinators, categorical labels, and
metadata batching behave correctly under brainstate.transform.jit and
brainstate.transform.vmap2. The package now ships inline type information
(PEP 561), test coverage is raised to ~92%, and documentation links and
assets are migrated to the new brainx.chaobrain.com host.
Highlights#
New optimizers
SOFOandSOFOScan: Second-Order Forward-mode Optimization for feedforward and recurrent models. Both build a Generalised Gauss-Newton matrix in a random tangent subspace from forward-mode JVPs and apply the resulting direction through the standard optax update path, so learning-rate schedules, momentum, weight decay, and gradient clipping continue to work unchanged.Hardened
cogtaskdispatch:Switchnow works in both eager and traced execution,Whilefails loudly on unsupported traced conditions, and a newnum_classesparameter decouples categorical-head sizing fromnum_outputs.PEP 561 typing:
braintoolsships apy.typedmarker and inline annotations on its public API, so downstream static type checkers consume its types directly.
Added#
braintools.optim — forward-mode second-order optimizers#
SOFO: Second-Order Forward-mode Optimization for a modelmodel(inputs) -> predictionspaired withloss_fn(predictions, targets). It samples random tangent vectors, takes forward-mode JVPs through the model and loss, builds a damped Generalised Gauss-Newton system in the random subspace, solves it, and projects the solution back to parameter space. Supports'mse'and'ce'loss forms, a configurabletangent_sizeanddamping,momentum/nesterov, decoupledweight_decay, and norm/value gradient clipping.SOFOScan: a recurrent variant for a stateful one-step cellrnn_cell(latent, inputs) -> (new_latent, output). The cell is scanned over the input sequence withbrainstate.transform.scan, and forward-mode JVPs propagate the tangents throughlax.scan, accumulating the Gauss-Newton matrix over every(timestep, batch)sample before a single solve. Both optimizers are exported frombraintools.optimand documented in the API reference.
braintools.cogtask#
Taskcategorical sizing: a newnum_classesargument, decoupled fromnum_outputs, sizes categorical output heads independently of the raw output dimension.Taskfeature ergonomics:Tasknow accepts a loneFeaturein place of aFeatureSet, and requires features to be supplied wheneverphasesare given.Tasktime step:Taskandmake_taskaccept an optionaldtargument. When set, it is pinned around trial generation viabrainstate.environ.context, so phase durations and buffer sizes are computed against thatdtand the reporteddtstays consistent regardless of the ambient environment. When omitted, the ambientbrainstate.environ.get_dt()is used (unchanged behaviour).
Typing#
PEP 561 support: a
braintools/py.typedmarker is shipped via package data, and the top-level public API — spike bitwise ops, spike encoders (with implicit-Optionaldefaults fixed), tree utilities, and_mischelpers — now carries resolvable inline annotations.
Changed#
cogtaskconditional dispatch:Switchuses dual-mode packed dispatch — a concretekey in caseslookup in eager mode and alax.switchover ordered branches underjit/vmap— and coerces 0-d concrete array keys (e.g.ctx.rng.choice(...)selectors) so eagersample_trialno longer raisesunhashable type: 'ArrayImpl'.Whileraises a clearNotImplementedErrorfor data-dependent (traced) conditions underjit/vmapinstead of surfacing a crypticTracerBoolConversionError.
Documentation links: chaobrain-ecosystem documentation URLs (
brainstate,brainunit,braincell,brainmass,brainevent,braintrace,braintools, and related packages) were rewritten from*.readthedocs.ioto the newbrainx.chaobrain.comhost, stripping/latest,/en/latest, and/en/stablepath prefixes and?badge=latestquery strings. Third-party ReadTheDocs links are left intact.README logo: the project logo is now served from
brainx.chaobrain.comas WebP instead of a raw GitHub asset.
Fixed#
braintools.cogtask:Categorical labels that are statically out of range for the declared
num_classesare now validated and rejected up front.Packed-mode phases expose
phase_start/phase_endbeforeon_enterruns, matching the contract already provided in fixed-length mode.String leaves are dropped from batched metadata so
return_metaworks correctly underbrainstate.transform.vmap2.Minor fixes to the input encoder and the working-memory task library.
Added regression tests covering all of the above.
braintools.trainer:LightningModule.deviceno longer raises on array-backed parameters;Array.devices()returns a set, which is now handled correctly (#92).ModelCheckpointsaves throughbraintools.file.msgpack_saveinstead of a state-restore helper, so checkpoints are written correctly (#95).
braintools.visualize:animate_2Dreshapes the value grid before drawing the first frame, fixing apcolorcrash on the initial step (#93).correlation_matrix(method='kendall')builds the matrix pairwise instead of passing a 2-D array tokendalltau(#94).remove_axisusesax.spinesinstead of the non-existentax.spine(#96).create_neural_colormap/brain_colormapsregister withforce=True, making them idempotent rather than raising on re-use (#97).roc_curve/precision_recall_curveresolvenp.trapezoidwhen available (falling back tonp.trapz), fixing anAttributeErroron NumPy >= 2.4 wherenp.trapzwas removed (#99).
Infrastructure#
Publish workflow: reads the package version directly from
braintools/_version.py(the single source of truth) and verifies that the release tag matches before publishing.Docs deployment: the
push: maintrigger was removed; documentation is now deployed only on a GitHub release (released) or via a manualworkflow_dispatch.Type-check workflow: a new Type Check workflow runs
mypyover the annotated public surface, backed by a[tool.mypy]configuration and atype-checkoptional-dependency group.Test coverage: new test suites cover the previously-untested trainer, visualize, file, and surrogate modules, raising overall coverage to ~92%. CI runs
pytestwith--covand uploads results to Codecov, and the README carries a coverage badge.tqdmandrichwere added to thetestingextra so the progress-bar tests run in CI.
Version 0.1.9 (2026-05-21)#
This release introduces braintools.cogtask, a composable framework for
constructing cognitive tasks for neural-network training and computational
neuroscience experiments. It also extends braintools.init to accept
brainstate.nn.Param, adds official Python 3.14 support, and refreshes
documentation and CI infrastructure.
Highlights#
New module
braintools.cogtask: a phase-based DSL for building trial-structured cognitive tasks, with a library of pre-built paradigms drawn from the cognitive-neuroscience literature.Variable-length trials under JIT/vmap: shape-stable packed-mode trial generation enables
batch_sampleto remain compatible withbrainstate.transform.jitandbrainstate.transform.vmap2for tasks whose phases have data-dependent durations.Python 3.14 support: CI matrix and project metadata updated; minimum supported Python remains 3.11.
Added#
braintools.cogtask — composable cognitive task framework#
Core API:
Task,TaskConfig,Context,Phase,Sequence,Repeat,Parallel, conditional combinatorsIf/Switch/While, and theconcathelper for sequential composition.Phase primitives:
Fixation,Delay,Stimulus,Response,Cue, plus the variable-lengthVariableDurationphase whose timestep budget is resolved per-trial from a context entry.Feature and label utilities:
Feature,circular,one_hot, and a set of input encoders/decoders for constructing task observations and targets in a typed, composable way.Pre-built task library spanning three domains:
Decision making:
PerceptualDecisionMaking,PerceptualDecisionMakingDelayResponse,ContextDecisionMaking,SingleContextDecisionMaking,PulseDecisionMaking.Working memory:
DelayMatchSample,DualDelayMatchSample,DelayComparison,DelayMatchCategory,DelayPairedAssociation,GoNoGo,IntervalDiscrimination,PostDecisionWager,ReadySetGo,DelayDirectionReproduction,ImmediateDirectionReproduction,DelayDirectionClassification,ImmediateDirectionClassification.Motor and reasoning:
AntiReach,Reaching1D,EvidenceAccumulation,HierarchicalReasoning,ProbabilisticReasoning.
Variable-length trial sequences:
VariableDurationphases declare a Pythonmax_steps(used as the buffer slot size) and report the realised trial length via the tracedstep_countfield.Taskauto-detects variable-length phase trees viaphase_tree_is_variable(phases). When any phase declaresis_variable = True,sample_trialallocates buffers of sizetask.max_trial_duration(), writes only the frontt_cursortimesteps, and zero-fills the trailing positions while setting the mask toFalse.Task.batch_sample(..., return_mask=True)returns(X, Y, mask)with shape-stable buffers underbrainstate.transform.jitandbrainstate.transform.vmap2. Fixed-length tasks remain unaffected;return_mask=Trueon a fixed task yields an all-Truemask.Ifusesjax.lax.condso both branches contribute shape-stable output;SwitchandWhileuse Python dispatch (concrete keys / Pythonboolconditions) and zero-pad to the static maximum.HierarchicalReasoning,IntervalDiscrimination, andReadySetGohave been migrated toVariableDurationand are now usable underbatch_samplewith masking — previously they were valid only viasample_trialand were not vmap-safe.Duration samplers
TruncExpandUniformDurationadvertiseis_variable = Trueand exposemax_value()/min_value()so phases can size their slots statically from sampler bounds.
Other additions#
braintools.init.param: now acceptsbrainstate.nn.Paraminstances in addition to plain initializers, enabling reuse of pre-built parameter objects when constructing layers..gitattributes: normalises line endings for text files to keep diffs and tooling consistent across platforms.
Changed#
Python support: project metadata, CI matrix, and classifiers updated to include Python 3.14. Minimum supported Python remains 3.11.
Documentation hosting: docs are now self-hosted at
brainx.chaobrain.com/braintools/; the documentation deployment workflow publishes on GitHub release events, while pushes tomainrun a build-only verification step.Documentation dependencies: bumped
sphinx(>=5→>=9.0.4),sphinx-book-theme(>=1.0.1→>=1.2.0),sphinx-copybutton(>=0.5.0→>=0.5.2),jupyter-sphinx(>=0.3.2→>=0.5.3), andbrainx-sphinx-header.
Fixed#
braintools.cogtaskend-to-end correctness pass (introduced together with the module):Renamed
cogtask/typing.pytocogtask/_typing.pyso the local module no longer shadows the stdlibtypingwhen tests run from inside the package; updated the absolute import infeature.pyto the relativefrom ._typing import Data.Added the missing
noise_sigmaargument and attribute toPerceptualDecisionMaking,PerceptualDecisionMakingDelayResponse,ContextDecisionMaking,SingleContextDecisionMaking,AntiReach,Reaching1D,EvidenceAccumulation,DelayPairedAssociation,GoNoGo, andPostDecisionWager, which previously raisedAttributeErroras soon asdefine_phasesran.Removed a duplicate
Task.__repr__and an undocumentedTaskLoadersymbol from the public docs.
Phase engine: added an
IS_COMPOUNDflag onPhaseand a uniformchildren()traversal hook.execute_phasenow dispatchesSequence/Repeat/Parallel/If/Switch/Whileto their ownexecute()methods; previously,If/Switch/Whilesilently no-op’d.Parallel.executenow gives each child its own[phase_start, phase_start + duration)window.Distance-profile tests: representation-equality checks corrected so the test suite is stable across NumPy/JAX representations.
Infrastructure#
Bumped GitHub Actions:
actions/checkout4 → 6,actions/setup-python5 → 6,actions/download-artifact5 → 8,actions/upload-artifact6 → 7,appleboy/ssh-action1.2.0 → 1.2.5,appleboy/scp-action0.1.7 → 1.0.0.Refactored version management: a dedicated
braintools/_version.pymodule is now the single source of truth, andpyproject.tomlresolves the package version viaattr = "braintools._version.__version__".
Version 0.1.7 (2026-01-05)#
Major Features#
New Training Framework (braintools.trainer)#
PyTorch Lightning-like training API for JAX-based neural network training with comprehensive features:
LightningModule: Base class for defining training models with
training_step(),validation_step(), andconfigure_optimizers()hooksTrainer: Orchestration class for managing training loops, epochs, and device placement
TrainOutput/EvalOutput: Structured output types for training and evaluation results
Callbacks System#
10+ built-in callbacks for customizing training behavior:
ModelCheckpoint: Automatic model saving based on monitored metricsEarlyStopping: Stop training when metrics plateauLearningRateMonitor: Track and log learning rate changesGradientClipCallback: Gradient clipping for training stabilityTimer: Track training timeRichProgressBar/TQDMProgressBar: Visual progress indicatorsLambdaCallback/PrintCallback: Custom callback utilities
Logging Backends#
6 pluggable logging backends:
TensorBoardLogger: TensorBoard integrationWandBLogger: Weights & Biases integrationCSVLogger: Simple CSV file loggingNeptuneLogger: Neptune.ai integrationMLFlowLogger: MLFlow integrationCompositeLogger: Combine multiple loggers
Data Loading Utilities#
JAX-compatible data loading with distributed support:
DataLoader/DistributedDataLoader: Efficient batch loadingDataset,ArrayDataset,DictDataset,IterableDataset: Dataset abstractionsSampler,RandomSampler,SequentialSampler,BatchSampler,DistributedSampler: Sampling strategies
Distributed Training#
Multi-device and multi-host training strategies:
SingleDeviceStrategy: Single device executionDataParallelStrategy: Data parallelism across devicesShardedDataParallelStrategy/FullyShardedDataParallelStrategy: Memory-efficient sharded trainingAutoStrategy: Automatic strategy selectionall_reduce,broadcast: Distributed communication primitives
Checkpointing#
Comprehensive checkpoint management:
CheckpointManager: Manage multiple checkpoints with retention policiessave_checkpoint/load_checkpoint: Save and restore model statesfind_checkpoint/list_checkpoints: Checkpoint discovery utilities
Progress Bar System#
Multiple progress bar implementations:
SimpleProgressBar: Basic text-based progressTQDMProgressBarWrapper: TQDM-based progressRichProgressBarWrapper: Rich library-based progress
Improvements#
API Documentation#
Enhanced module documentation: All public modules now include comprehensive docstrings with examples, parameter descriptions, and usage guidelines directly in
__init__.pyfilesReorganized imports: Cleaner and more consistent import structure across all modules
Breaking Changes#
Removed braintools.param Module#
The entire
braintools.parammodule has been removed, including:Data containers (
Data)Parameter wrappers (
Param,Const)State containers (
ArrayHidden,ArrayParam)Regularization classes (
GaussianReg,L1Reg,L2Reg)All transform classes (
SigmoidT,SoftplusT,AffineT, etc.)Utility functions (
get_param(),get_size())
Users relying on these features should migrate to alternative implementations or pin to version 0.1.6
Version 0.1.6 (2025-12-25)#
New Features#
Parameter Management Expansion (braintools.param)#
Hierarchical data container: Added
Datafor composed state storage and cloning.Parameter wrappers: Added
ParamandConstwith built-in transforms and optional regularization.State containers: Added
ArrayHiddenandArrayParamwith transform-aware.dataaccess.Regularization priors: Added
GaussianReg,L1Reg, andL2Regwith optional trainable hyperparameters.Utilities: Added
get_param()andget_size()helpers for parameter/state handling.
Transforms#
New
ReluTtransform for lower-bounded parameters.Expanded transform suite now includes
PositiveT,NegativeT,ScaledSigmoidT,PowerT,OrderedT,SimplexT, andUnitVectorT.
Improvements#
API Consistency#
Transform naming cleanup: Standardized transform class names with the
*Tsuffix (e.g.,SigmoidT,SoftplusT,AffineT,ChainT,MaskedT,ClipT).
Documentation#
Expanded param API docs: Added sections for data containers, state containers, regularization, utilities, and updated transform listings in
docs/apis/param.rst.API index update: Added
paramAPI page todocs/index.rst.
Tests#
New test coverage: Added tests for data containers, modules, regularization, state, transforms, and utilities across the param module.
Breaking Changes#
Transform API renames: Transform classes now use the
*Tsuffix (e.g.,Sigmoid->SigmoidT).Custom transform removed: The
Customtransform is no longer part of the public API.
Bug Fixes#
Initializer RNG:
TruncatedNormalnow defaults tonumpy.randomwhen no RNG is provided.
Version 0.1.5 (2025-12-14)#
New Features#
Parameter Transformation Module (braintools.param)#
7 new bijective transforms for constrained optimization and probabilistic modeling:
Positive: Constrains parameters to (0, +∞) using exponential transformation
Negative: Constrains parameters to (-∞, 0) using negative softplus
ScaledSigmoid: Sigmoid with adjustable sharpness/temperature parameter (beta)
Power: Box-Cox family power transformation for variance stabilization
Ordered: Ensures monotonically increasing output vectors (useful for cutpoints in ordinal regression)
Simplex: Stick-breaking transformation for probability vectors summing to 1
UnitVector: Projects vectors onto the unit sphere (L2 norm = 1)
Jacobian computation: Added
log_abs_det_jacobian()method to Transform base class and implementations for probabilistic modelingImplemented for: Identity, Sigmoid, Softplus, Log, Exp, Affine, Chain, Positive
Surrogate Gradient Enhancements (braintools.surrogate)#
Gradient computation of hyperparameters of surrogate gradient functions.
Fix batching issue in surrogate gradient functions
Improvements#
API Enhancements#
__repr__methods: Added string representations to all Transform classes and Param class for better debuggingEnhanced documentation: Updated
docs/apis/param.rstwith comprehensive API referenceOrganized sections: Base Classes, Parameter Wrapper, Bounded Transforms, Positive/Negative Transforms, Advanced Transforms, Composition Transforms
Descriptive explanations for each transform’s use case
Code Quality#
Comprehensive test coverage: Added 28 new tests for param module (45 total tests passing)
Tests for all new transforms: roundtrip, constraints, repr methods
Tests for
log_abs_det_jacobiancorrectnessTests for edge cases and numerical stability
Version 0.1.4 (2025-10-31)#
New Features#
Learning Rate Scheduler Enhancements (braintools.optim)#
New
apply()method: Addedapply()method to all LR schedulers for more flexible learning rate applicationAllows applying learning rate transformations without stepping the scheduler
Useful for custom training loops and learning rate inspection
Comprehensive test coverage: Added 118+ comprehensive tests covering all 17 learning rate schedulers
Tests for basic functionality, optimizer integration, JIT compilation, state persistence
Full coverage of edge cases and special modes for each scheduler
Validates correctness with
@brainstate.transform.jitcompilation
Improvements#
Documentation#
Restructured tutorial organization: Renamed and reorganized documentation files for better clarity
Moved module tutorials into subdirectories (
conn/,init/,input/,file/,surrogate/)Updated table of contents structure across all modules
Improved navigation with consolidated index files (
index.mdinstead oftoc_*.md)
Enhanced visual branding: Updated project logo from JPG to high-resolution PNG format
Better quality and transparency support
Consistent branding across documentation
Code Quality#
Test improvements: Refactored scheduler tests with better organization and coverage
Each scheduler now has 5-10 dedicated tests
Tests verify: basic functionality, optimizer integration, JIT compilation, multiple param groups, state dict save/load
Discovered and documented key implementation behaviors (epoch counting, initialization patterns)
CI/CD#
Updated GitHub Actions: Bumped actions to latest versions for improved security and performance
actions/download-artifact: v5 → v6actions/upload-artifact: v4 → v5Better artifact handling in CI pipeline
Bug Fixes#
Fixed edge cases in learning rate scheduler state management
Corrected epoch counting behavior in milestone-based schedulers
Improved JIT compilation compatibility for all schedulers
Notes#
All 17 learning rate schedulers now have comprehensive test coverage (100%)
Enhanced reliability for training workflows with thorough validation
Improved developer experience with better documentation structure
Version 0.1.0 (2025-10-06)#
Major Features#
Surrogate Gradients Module (braintools.surrogate)#
New comprehensive surrogate gradient system for training spiking neural networks (SNNs)
18+ surrogate gradient functions with straight-through estimator support:
Sigmoid-based:
Sigmoid,SoftSign,Arctan,ERFPiecewise:
PiecewiseQuadratic,PiecewiseExp,PiecewiseLeakyReluReLU-based:
ReluGrad,LeakyRelu,LogTailedReluDistribution-inspired:
GaussianGrad,MultiGaussianGrad,InvSquareGrad,SlayerGradAdvanced:
S2NN,QPseudoSpike,SquarewaveFourierSeries,NonzeroSignLog
Customizable hyperparameters (alpha, sigma, width, etc.) for fine-tuning gradient behavior
Comprehensive tutorials: 2 detailed notebooks covering basics and customization
Enables gradient-based training of SNNs via backpropagation through time
Over 2,600 lines of implementation with extensive test coverage
New Features#
Learning Rate Schedulers (braintools.optim)#
ExponentialDecayLR scheduler: Fine-grained exponential decay with step-based control
Support for transition steps, staircase mode, delayed start, and bounded decay
Better control than epoch-based ExponentialLR for step-level scheduling
Compatible with Optax’s exponential_decay schedule
Improvements#
API Refinements#
Deprecation warnings added for future API changes:
Deprecated
beta1andbeta2parameters in Adam optimizer (useb1andb2instead)Deprecated
unitparameter in various initializers (useUNITLESSby default)Deprecated
init_callfunction replaced withparamfor improved consistency
Enhanced state management: Refactored
UniqueStateManagerto utilize pytree methodsComprehensive tests: Added extensive tests for
UniqueStateManagermethods and edge cases
Documentation#
Updated API documentation for new surrogate gradient module
Added learning rate scheduler documentation for
ExponentialDecayLREnhanced optimizer tutorials with updated examples
Clarified docstrings for
FixedProbclass and variance scaling initializer
Code Quality#
Internal Improvements#
Updated copyright information from BDP Ecosystem Limited to BrainX Ecosystem Limited
Improved consistency across codebase with standardized function signatures
Better default parameter handling (
UNITLESSfor unit parameters)Enhanced test coverage for state management and optimizers
Metric Enhancements#
Improved correlation and firing metrics implementation
Enhanced LFP (Local Field Potential) analysis functions
Better error handling and validation in metric computations
Breaking Changes#
Deprecation notices (not yet removed, but will be in future versions):
beta1/beta2parameters in Adam optimizer (useb1/b2)unitparameter in initializers (defaults toUNITLESS)init_callfunction (useparaminstead)
Notes#
This release focuses on enabling gradient-based training for spiking neural networks
The surrogate gradient module is a major addition for neuromorphic computing and SNN research
Enhanced learning rate scheduling provides more control for training workflows
Version 0.0.14 (2025-10-04)#
New Features#
Optimizer Enhancements (braintools.optim)#
Momentum optimizers: Added
MomentumandMomentumNesterovoptimizers with gradient transformationsImproved state management: Refactored optimizer state handling with new
OptimStateclass for better encapsulation
Initialization Updates (braintools.init)#
ZeroInit initializer: New zero initialization class for weights and parameters
VarianceScaling export: Added
VarianceScalingto module exports for easier access
Improvements#
Enhanced optimizer state management for better performance and maintainability
Simplified initialization API with additional export options
Updated documentation for new initialization methods
Internal Changes#
Refactored test structure for initialization module
Improved learning rate scheduler implementation
Version 0.0.13 (2025-10-02)#
Major Features#
New Initialization Framework (braintools.init)#
Unified initialization API consolidating all weight and parameter initialization strategies
Distance-based initialization: Support for distance-modulated weight patterns
Variance scaling strategies: Xavier, He, LeCun initialization methods
Orthogonal initialization for improved training stability
Composite distributions for complex initialization patterns
Simplified API with consistent parameter naming across all initializers
Advanced Connectivity Patterns (braintools.conn)#
Topological network patterns:
Small-world and scale-free networks
Hierarchical and core-periphery structures
Modular and clustered random connectivity
Enhanced biological connectivity:
Excitatory-inhibitory balanced networks
Distance-dependent connectivity with multiple profiles
Compartment-specific connectivity (dendrite, soma, axon)
Spatial connectivity improvements:
2D convolutional kernels for spatial networks
Position-based connectivity with normalization
Distance modulation using composable profiles
Comprehensive Optax Integration (braintools.optim)#
Full Optax optimizer support: Adam, SGD, RMSProp, AdaGrad, AdaDelta, and more
Advanced learning rate schedulers:
Cosine annealing with warm restarts
Polynomial decay with warmup
Piecewise constant schedules
Sequential and chained schedulers
Improved optimizer state management with unique state handling
Parameter groups with per-group learning rates
Improvements#
API Enhancements#
Simplified
connmodule API with direct class accessRefactored initialization calls for consistency
Improved type annotations throughout
Better default parameter handling
Documentation & Tutorials#
Updated tutorial structure for connectivity patterns
New examples for topological networks
Enhanced API documentation with detailed examples
Improved code readability in tutorials
Code Quality#
Comprehensive test coverage for new features
Better error handling and validation
Consistent naming conventions
Removed deprecated and redundant code
Breaking Changes#
Renamed
PointNeuronConnectivitytoPointConnectivityRenamed
ConvKerneltoConv2dKernelUnified initializer names (e.g.,
ConstantWeight→Constant)Removed
PopulationRateConnectivityclassChanged some parameter names for clarity (e.g., unified use of
rngparameter)
Version 0.0.12 (2025-09-24)#
Major Features#
Comprehensive Visualization System#
New visualization modules for neural data analysis:
neural.py: Spike rasters, population activity, connectivity matrices, firing rate mapsthree_d.py: 3D visualizations for neural networks, brain surfaces, trajectories, electrode arraysstatistical.py: Statistical plotting tools (confusion matrices, ROC curves, correlation plots)interactive.py: Interactive visualizations with Plotly supportcolormaps.py: Neural-specific colormaps and publication-ready styling
15+ new tutorial notebooks covering all visualization techniques
Brain-specific colormaps for membrane potential, spike activity, and connectivity
Enhanced Numerical Integration#
New ODE integrators:
Runge-Kutta methods: RK23, RK45, RKF45, DOP853, DOPRI5, SSPRK33
Specialized methods: Midpoint, Heun, RK4(3/8), Ralston RK2/RK3, Bogacki-Shampine
New SDE integrators: Heun, Tamed Euler, Implicit Euler, SRK2, SRK3, SRK4
IMEX integrators for stiff equations: Euler, ARS(2,2,2), CNAB
DDE integrators for delay differential equations
Comprehensive test coverage and accuracy verification
Advanced Spike Processing#
Spike encoders: Rate, Poisson, Population, Latency, and Temporal encoders
Enhanced spike operations with bitwise functionality
Spike metrics: Victor-Purpura distance, spike train synchrony, correlation indices
Tutorial notebooks for spike encoding and analysis
New Optimization Framework#
NevergradOptimizer: Integration with Nevergrad optimization library
ScipyOptimizer: Enhanced scipy optimization with flexible bounds support
Refactored optimizer architecture for better extensibility
Support for dict and sequence parameter bounds
Improvements#
File Management#
Enhanced msgpack serialization with mismatch handling options
Improved checkpoint loading with better error recovery
Support for handling mismatched keys during state restoration
Metrics and Analysis#
LFP analysis functions: Power spectral density, coherence analysis, phase-amplitude coupling
Functional connectivity: Dynamic connectivity computation
Classification metrics: Binary, multiclass, focal loss, and smoothing techniques
Regression losses: MSE, MAE, Huber, and quantile losses
Documentation#
Added comprehensive API documentation for all new modules
Created tutorials for:
ODE/SDE integration methods
Classification and regression losses
Pairwise and embedding similarity
Spiking metrics and LFP analysis
Advanced neural visualization techniques
Updated project description from “brain modeling” to “brain simulation”
Changed references from BrainPy to BrainTools throughout
Code Quality#
Added extensive unit tests for all new modules
Improved type hints and parameter documentation
Better error handling and validation
Consistent API design across modules
Breaking Changes#
Refactored optimizer module structure (moved from single
optimizer.pyto separate modules)Removed unused key parameter from spike encoder methods
Updated some function signatures for clarity
Bug Fixes#
Fixed Softplus unit scaling issues
Corrected paths in publish workflow
Fixed formatting in ODE integrator documentation
Resolved msgpack checkpoint handling errors