This article gives a Transformer architecture, quantile losses and evaluation examples for SOH and RUL. The preceding article separates PyBaMM degradation solves from the downloadable lab’s surrogate labels. The figure here comes from that lab’s RandomForestRegressor baseline, not a training run of the Transformer below.
SOH estimation needs a reference capacity and test conditions. RUL also depends on the failure threshold, future operating conditions and available input information. Evaluate the two tasks separately, including early life, the knee region and cross-cell performance.

PyBaMM battery modelling series · Data pipeline (part 4 of 5): Previous: Generate Battery Aging and EIS AI Datasets with PyBaMM · Next: Drive-Cycle Current in PyBaMM: Time Grids and a Charge Check · Series hub: Data pipeline (5) + Silent failures, measured (8) · RSS feed.
1. Degradation as a stochastic process
Observed battery behaviour can depend on history; a Markov representation depends on what the state contains. Including the relevant concentration and damage variables in \(x_k\) permits a nonlinear state-space model such as the one below. Gaussian process and measurement noise are assumptions here. An extended Kalman filter is one method for estimating states under the corresponding conditions.
State transition (SEI growth and loss of active material):
$$ x_{k+1} = f(x_k, u_k) + w_k, \quad w_k \sim \mathcal{N}(0, Q) $$
Observation (EIS spectra and terminal voltage):
$$ y_k = h(x_k, u_k) + v_k, \quad v_k \sim \mathcal{N}(0, R) $$
The state \(x_k\) can include lithium inventory and active-material fractions. A network may predict SOH/RUL directly or approximate a transition or observation function. Its objective depends on that design and noise assumptions; it need not always replace \(h(\cdot)\) and maximise a joint likelihood.
History windows can add information missing from one EIS observation. Compare a current-state baseline, history features and sequence models to choose the window. The word “non-Markovian” alone does not establish that every present-state input is inadequate.
2. What early-life RUL prediction depends on
Consider an illustration: two cells have similar capacity for their first 200 cycles. One develops a knee at cycle 400, while the other still fades slowly at cycle 800. At cycle 100, similar capacity observations may be hard to distinguish. A knee is not an end-of-life threshold, however; these numbers do not define true RUL or show that it differs by exactly a factor of two.
When inputs cannot distinguish future outcomes, the squared-loss optimum is a conditional mean. Whether early data contains useful signals is an empirical question, not a universal absence of information; published work predicts lifetime from early data for specified cells and protocols. Keep a point-estimate baseline and report stage-wise error and uncertainty.
Choose among the following outputs using task requirements, cost and validation:
| Approach | Output | Cost |
|---|---|---|
| Quantile regression | RUL at the 10/50/90th percentile; intervals widen naturally early on | Swap in pinball loss — essentially free |
| Classify into lifetime bands | “more than 500 / 200-500 / under 200 cycles left” | Loses resolution, but aligns with maintenance decisions |
| Only predict RUL below an SOH threshold | Restricted to the regime where information exists | No early output, which the application may not accept |
For MSE point regression, report stage- and condition-specific errors as well as an average, and compare interval or quantile outputs. Quantile regression also requires calibration checks; its early-life intervals do not widen automatically because of the loss alone.
3. A model definition that actually runs
The following defines a network; it does not supply data loading, a complete training loop or real-cell validation. It implements a sinusoidal PositionalEncoding class, while other position representations are possible. The default observation has 120 features, for example real and imaginary values at 60 frequencies.
import math
import torch
import torch.nn as nn
class PositionalEncoding(nn.Module):
"""Standard sinusoidal encoding. "Position" here is cycle index, not
wall-clock time - which only works for evenly spaced cycles. If your EIS
is measured at irregular intervals, feed delta-cycle as a feature instead
of relying on positional encoding."""
def __init__(self, d_model, max_len=5000):
super().__init__()
pe = torch.zeros(max_len, d_model)
pos = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(pos * div)
pe[:, 1::2] = torch.cos(pos * div)
self.register_buffer("pe", pe.unsqueeze(0)) # buffer, not parameter: no
# gradient, but saved with the model
def forward(self, x):
return x + self.pe[:, : x.size(1)]
class ImpedanceTransformer(nn.Module):
def __init__(self, input_dim=120, d_model=256, nhead=8, num_layers=4, n_quantiles=3):
super().__init__()
self.input_projection = nn.Linear(input_dim, d_model)
self.pos_encoder = PositionalEncoding(d_model)
layer = nn.TransformerEncoderLayer(
d_model=d_model, nhead=nhead,
dim_feedforward=4 * d_model,
batch_first=True, # without this the convention is [seq, batch, dim]
# and silently misaligns with the [batch, seq, dim] below
norm_first=True, # pre-LN, far more stable when deep
)
self.transformer = nn.TransformerEncoder(layer, num_layers=num_layers)
self.soh_head = nn.Linear(d_model, 1)
# RUL emits quantiles rather than a point estimate - see the previous section
self.rul_head = nn.Sequential(
nn.Linear(d_model, 64), nn.GELU(), nn.Linear(64, n_quantiles), nn.Softplus()
)
def forward(self, eis_sequence, pad_mask=None):
# eis_sequence: [batch, seq_len, input_dim]
# pad_mask: [batch, seq_len], True marks padding
x = self.pos_encoder(self.input_projection(eis_sequence))
feats = self.transformer(x, src_key_padding_mask=pad_mask)
if pad_mask is None:
latest = feats[:, -1, :]
else:
# For variable-length sequences [-1] is padding. Take the last valid step.
lengths = (~pad_mask).sum(dim=1) - 1
latest = feats[torch.arange(feats.size(0)), lengths]
# Quantiles must be monotone: cumulative sum guarantees q10 <= q50 <= q90
rul = torch.cumsum(self.rul_head(latest), dim=-1)
return self.soh_head(latest), rul
Here batch_first=True matches [batch, sequence, feature]. Variable-length inputs need contiguous right padding, at least one valid observation per row and length at most 5000; d_model must be even and divisible by nhead. Position denotes observation order. Irregular data should also represent actual cycles, time or gaps. Softplus plus cumulative sum makes the three RUL outputs non-negative and ordered, not automatically calibrated.
4. Training losses and output checks
$$ \mathcal{L}(\theta) = \lambda_1 \| \text{SOH}_{pred}-\text{SOH}_{true} \|_2^2 + \lambda_2 \mathcal{L}_{pinball}(\text{RUL}) + \lambda_3 \Phi(\widehat{\mathrm{SOH}}_{1:T}). $$
import torch
import torch.nn.functional as F
QUANTILES = torch.tensor([0.1, 0.5, 0.9])
def pinball_loss(pred, target, quantiles=QUANTILES):
"""pred: [batch, n_q] target: [batch, 1]"""
q = quantiles.to(pred.device).view(1, -1)
err = target - pred
return torch.maximum(q * err, (q - 1) * err).mean()
def monotonicity_penalty(soh_seq):
"""SOH must be non-increasing over cycles. Rest recovery causes small genuine
rebounds, so allow a tolerance band and only penalise rises beyond it - a hard
constraint would suppress real physics."""
diff = soh_seq[:, 1:] - soh_seq[:, :-1]
return F.relu(diff - 0.002).pow(2).mean()
def total_loss(soh_pred, rul_pred, soh_true, rul_true, soh_seq,
l1=1.0, l2=0.5, l3=0.1):
return (l1 * F.mse_loss(soh_pred, soh_true)
+ l2 * pinball_loss(rul_pred, rul_true)
+ l3 * monotonicity_penalty(soh_seq))
The loss defaults to q10/q50/q90. If n_quantiles changes, change QUANTILES too and keep targets shaped [batch, 1]. The linear SOH head has no range constraint; check predictions against the capacity definition rather than treating the penalty as proof of all physical constraints.
The value 0.002 is an example regularisation hyperparameter, not a universal recovery threshold. Supply a differentiable sequence of predictions as soh_seq, excluding padding and containing at least two times. At length one the preserved function averages an empty tensor and returns NaN. The forward method above emits only the latest estimate, so the caller must construct these sequence predictions without using data unavailable at the prediction time.
5. Covariate shift and leakage
For generalisation to new cells, split by independent trajectory or design. Adjacent cycles \(N\) and \(N+1\) across train and test can reward local interpolation. This changes the evaluation task; it does not alone establish inevitable failure on real hardware.
import numpy as np
from sklearn.model_selection import GroupKFold
groups = metadata["cell_design_id"].values
gkf = GroupKFold(n_splits=5)
for fold, (tr, te) in enumerate(gkf.split(X, y, groups=groups)):
# Assert in the pipeline. Discovering implausibly good metrics later costs more.
assert not (set(groups[tr]) & set(groups[te])), f"group leak in fold {fold}"
...
There is a subtler leak: feature normalisation. Computing mean and standard deviation over the full dataset before splitting bleeds test statistics into training. Normalisation parameters must come from the training fold alone, then be applied to the test fold.
6. Evaluation: one average error will lie to you
What makes battery life prediction hard is early-life uncertainty, error near the knee, and cross-cell generalisation. Reporting only RUL MAE conceals all three.
The two original tables retain example options and metrics. Validate whether early quantile intervals widen; monotonicity is an optional regulariser, not a hard rule for every measured capacity. A group gap may also reflect a genuine distribution shift and does not itself prove leakage.
| Metric | What it examines | Why it matters |
|---|---|---|
| SOH MAE / RMSE | Continuous health-state error | Overall capacity tracking accuracy |
| RUL error by life stage | Early / mid / late reported separately | A single average lets strong late-life numbers mask early-life failure |
| Quantile coverage | Fraction of truths inside [q10, q90] | Should sit near 80%; well below means uncertainty is understated |
| Knee point error | Displacement of the fade inflection | Determines whether the maintenance window is trustworthy |
| Group split gap | Within-cell vs across-cell test performance | A large gap indicates trajectory leakage or fake generalisation |
| Monotonicity violation | Implausible SOH rebounds | Checks the model against basic degradation physics |
If [q10,q90] covers only 45% of truths, it misses its nominal 80% coverage. Also report sample count, interval width and stage-wise coverage. Trading those properties against another model’s MAE needs decision costs, not a universal production-risk ranking.
7. Deploying to a BMS: quantisation is not free
BMS compute resources depend on hardware and system design; there is no universal sub-100-MHz ceiling. Check target MCU/SoC RAM, Flash, operators, latency and safety requirements. INT8, pruning and ONNX are options; an exported format does not establish that the target can execute it.
INT8 PTQ needs calibration data representative of intended conditions and independent comparisons of outputs and task metrics before and after quantisation. The additional error depends on the model, operators, backend and input distribution.
Mapped onto batteries, quantisation validation has to cover these regions separately:
- Samples near the knee — report SOH/RUL errors and interval coverage separately and compare before and after quantisation.
- Low-temperature operation — spectra differ markedly from room temperature and activation distributions shift
- Degradation pathways rare in the training set, such as plating-dominated rather than SEI-dominated cells
Cover expected conditions in calibration and testing. If INT8 errors are unacceptable in critical regions, compare quantisation-aware training, other precision or a smaller model on the target backend. FP16 uses twice the element bytes of INT8; package size, latency and behaviour also depend on operators and metadata. FP16 does not automatically restore reliable predictions.
8. Experiment record template
Data source: PyBaMM DFN/SPMe + measured calibration set
Parameter set: OKane2022 (degradation) / self-fitted
Split: GroupKFold by cell_design_id / protocol_id
Normalisation: computed on training fold only, applied to test fold
Input window: last N EIS spectra + temperature + DOD + C-rate
Targets: SOH (point), RUL (q10/q50/q90)
Key metrics: SOH MAE, stage-wise RUL MAE, quantile coverage, knee point error
Leak check: assert no group overlap between train and test
Quant check: knee / low-temp / rare pathway reported separately
Deployment: ONNX / int8 or fp16 / MCU latency budget
Use the template to connect data provenance, evaluation task and deployment budget. Record the actual models, labels, splits and quantisation results, then assess transfer on independent cells and conditions.
References
- Python Battery Mathematical Modelling (PyBaMM)
- PyTorch TransformerEncoder
- PyBOP: battery model optimisation and parameterisation
- Synthetic dataset of LG M50 batteries with different degradation pathways
- Severson et al.: Data-driven prediction of battery cycle life before capacity degradation
- ONNX Runtime: calibration and quantisation validation
- Infineon: AURIX microcontroller generations and BMS applications
A tool I built
Validate your cell model on independent data
VoltSift is an online workspace I built. Upload three CSV files (a fitting record, an independent validation record and an open-circuit voltage curve), and it fits a cell model, checks voltage error and coverage on the held-out record, and produces a report. The standard workflow supports single NMC cells at 25°C and SOC 20%–100%. Register and verify your email to get one free analysis, available for seven days.
Visit VoltSift · Prepare the three CSV files · How to read the validation results