APDTFlow v0.4.0: From a Critical Bug to Forecasting “When”
From the publisher’s feed, collected in the ZeroLabs newsroom.
https://github.com/yotambraun/APDTFlowThis is the third article about APDTFlow, my open-source time series forecasting package. The previous ones covered the basics and the v0.3.0 production features. This release is different. It started with a bug report that wasn’t even a bug report.In November, someone opened an issue on the repo asking a simple question: do you have documentation that discusses your implementation and design choices in more detail?I started writing that document. To write it properly, I had to re-verify the benchmarks. And while doing that, I found a bug that invalidated basically everything the package had published until then.This article covers what the bug was, how I rebuilt the model, the new continuous-time API that came out of the rebuild (including predict_when, which I think is the most useful thing in the package now), and the benchmark results on real NASA data. Including the one benchmark where a linear baseline beats my model. That stays in.The bugIn all versions up to 0.3.x, the model had use_embedding=True as the default. The embedding was supposed to enrich the input with learned time features. Instead, due to how the forward pass was written, it replaced the input series entirely with a time-index embedding that was identical for every sample.In plain terms: the model’s predictions did not depend on the input data.The test that confirmed it is two lines of thinking. Feed the model a smooth sine wave. Then feed it pure noise with 100x the amplitude. A working forecaster produces very different outputs. The buggy model produced the same output for both, with a standard deviation across inputs of exactly 0.0000.https://github.com/yotambraun/APDTFlow/blob/main/assets/images/apdtflow_fix_proof.pngThis is about as bad as a forecasting bug can get, and it explains symptoms I had been attributing to other causes, like flat forecasts on seasonal data. The training loss went down (the model was learning the average shape of the training targets), validation plots looked plausible at a glance, and the unit tests passed because none of them checked input sensitivity. The benchmark plots in the old README were generated by this model, so they were meaningless, and I deleted them.There is now a regression test in tests/test_learning.py that feeds the model two different inputs and fails if the outputs match. It runs in CI on every commit. If you take one thing from this article, take that test. It costs nothing and it catches an entire class of silent failures.One practical consequence for existing users: checkpoints saved from versions 0.3.x and earlier cannot be repaired. Loading one in v0.4.0 raises an error with instructions. You need to retrain, which with the fixed model is worth doing anyway.The rebuildFixing the embedding line alone got the model from “ignores its inputs” to “mediocre”. Getting it to actually compete required a few more architectural changes, each one benchmarked before it stayed:The decoder now attends over the full encoded latent trajectory instead of a single summary vector. There is a direct linear skip connection from the input window to the forecast, in the spirit of N-BEATS and the DLinear results, so the network only has to learn the residual that a linear map cannot express. The scale fusion is computed per timestep. And the default ODE solver is now fixed-step RK4, which is roughly 10x faster on CPU than the adaptive adjoint method with no accuracy loss I could measure.On the synthetic benchmark where the buggy model scored an MAE of 10.16, the rebuilt model scores 0.75, which is below the seasonal-naive baseline (MASE 0.61). Numbers like that mostly tell you the model now works at all. The interesting results come later, on real data.The part I actually wanted to build: predict_whenHere is the thing that kept me motivated through the rebuild. Almost every forecasting library answers one question: what will the value be at step k? But in a lot of real problems, the question people actually have is different. When will this battery reach end of life? When does this engine cross the maintenance threshold? When does inventory run out?You can hack an answer from a grid forecast by checking where the predicted curve crosses a line. But you get no uncertainty on the time itself, and the naive approach is miscalibrated in ways that bite (more on that below).Because APDTFlow’s latent dynamics are a Neural ODE, the trajectory between grid steps actually exists. v0.4.0 adds a continuous decoder on top of it, and three questions become one trained model:from apdtflow import APDTFlowForecastermodel = APDTFlowForecaster(forecast_horizon=40, decoder_type='continuous', use_conformal=True)model.fit(df, target_col='capacity')model.predict() # the classic grid forecastmodel.predict_at(['2026-06-11 14:37', 3.6]) # value at any moment, even # beyond the trained horizonresult = model.predict_when(threshold=1.4, direction='below')result.eta # point estimate: when does it cross?result.act_by # earliest edge of the calibrated windowresult.censored # True if no crossing within the horizonTwo implementation details turned out to matter a lot.First, calibration has to happen in time space. My first version mapped the value-space conformal band onto the time axis. On a test fixture with a 95% target, it achieved 32% coverage, because the mapping breaks whenever trajectories are steep or flat. Calibrating directly on crossing-time errors (take the signed differences between predicted and actual crossing times on a calibration split, use their quantiles) fixed it.Second, the errors are systematically asymmetric. On smoothed degradation indicators the point estimate runs late, so the calibrated window is asymmetric around it. That is why the API returns act_by as a first-class field. The operational rule, validated on the fleet benchmark below, is: schedule by act_by, never by the point estimate.Benchmarks on real NASA data, losses includedEvery number below is produced by a committed script in experiments/ and saved to a JSON next to it. The evaluation is deliberately hostile: models are trained on some units and audited on units they never saw, against persistence ("it crosses now or never"), linear extrapolation of the recent window, and seasonal baselines where relevant. A predicted "no crossing" when one happens is scored at the full horizon.Battery end of life (NASA battery dataset, 3 cells, leave-one-battery-out, threshold 1.4 Ah). Timing error in measured cycles: APDTFlow 8.3, linear extrapolation 9.7, persistence 15.4. The calibrated 90% window achieved 96% coverage on the held-out cell B0005, where the timing error was 2.8 cycles. The third cell, B0007, never reaches end of life inside the horizon, which makes it a censoring test: the model correctly returned “no crossing” on 42 of 109 windows and false-alarmed on the rest. That number is in the results JSON too.https://github.com/yotambraun/APDTFlow/blob/main/assets/images/apdtflow_battery_eol.pngTurbofan engines, FD001 (NASA C-MAPSS, 60 training engines, 40 unseen engines, 271 real threshold crossings). Timing error: APDTFlow 8.3, linear 8.7, persistence 11.5, with a 0.6% false alarm rate across 1,719 windows where nothing was about to happen.Turbofan engines, FD002, which is the hard one: 110 unseen engines operating across 6 different regimes. Here APDTFlow scores 9.2 cycles against linear extrapolation’s 8.1. That is a loss, and it is published as a loss in the README. The model does win the matched subset where both methods commit to an estimate (6.8 vs 7.8 cycles), and it posts zero false alarms across 2,638 no-crossing windows, which in a maintenance setting is the property that decides whether anyone trusts your alerts. But on the full-set point timing, the linear baseline is sharper on this dataset, and pretending otherwise would defeat the purpose of the whole exercise.https://github.com/yotambraun/APDTFlow/blob/main/assets/images/apdtflow_evidence_summary.pngThere is also a fleet API. One call takes a dictionary of asset histories and returns a maintenance schedule sorted by act-by date:schedule = model.predict_when_fleet(assets, threshold=1.4, direction='below')On a snapshot of all 110 FD002 engines, the calibrated windows covered 81% of the actual crossings.Things I tested and rejectedThe methodology doc keeps a list of ideas that were implemented, benchmarked, and cut. A few of them, because negative results are where most of the lessons were:Feeding the model a missingness mask plus time-since-last-observation features made accuracy worse than plain forward-fill imputation at 30% and 50% missingness. An ODE-RNN encoder for irregularly sampled data lost to every baseline including linear regression on forward-filled data, which matches recent literature, so the package makes no irregular-sampling claims (the old README did; that claim is gone). And event timing on noise-driven crossings, like which exact day a noisy daily series first dips below a value, is not forecastable by anything I tested, so the docs explicitly tell you not to use predict_when for that.The README now has a “When NOT to use APDTFlow” section. It includes stock prices.Everything else in 0.4.0Beyond the fix and the continuous-time API: multivariate input with a learned sensor fusion layer (fit(..., feature_cols=[...])) that exposes interpretable weights via sensor_importance_, per-regime normalization for multi-condition equipment, robust save/load that carries scalers and calibration state, TorchScript export, a FastAPI serving example, sklearn-style get/set params, a score_recent() drift hook, deterministic seeding, and a methodology document with full references. The changelog has the complete list.pip install --upgrade apdtflowIf you have degradation or depletion data of your own, experiments/audit_predict_when.py runs the same adversarial audit against the same baselines on your series. If APDTFlow wins on your domain, open a PR and I will feature it with your numbers. And if you find a problem, open an issue. The last person who did changed the entire project.ReferencesChen, R. T. Q., Rubanova, Y., Bettencourt, J., & Duvenaud, D. (2018). Neural Ordinary Differential Equations. NeurIPS. The foundation for modeling latent dynamics in continuous time, which is what makes querying arbitrary timestamps possible at all.Lim, B., Arik, S. O., Loeff, N., & Pfister, T. (2021). Temporal Fusion Transformers for Interpretable Multi-horizon Time Series Forecasting. IJF. The gated residual network design that APDTFlow’s time embedding follows (correctly, this time).Oreshkin, B. N., Carpov, D., Chapados, N., & Bengio, Y. (2020). N-BEATS. ICLR. And Zeng, A. et al. (2023), the DLinear paper. Together they are the reason the rebuilt model has a direct linear skip from input to forecast: linear maps are a strong backbone, and the network should learn the residual.Vovk, V., Gammerman, A., & Shafer, G. (2005). Algorithmic Learning in a Random World. Plus Romano et al. (2019) and Gibbs & Candès (2021) for the conformal prediction machinery behind every uncertainty window in the package.Hyndman, R. J., & Koehler, A. B. (2006). Another look at measures of forecast accuracy. IJF. The MASE metric used throughout the benchmarks.The full reference list and the per-component design discussion are in docs/METHODOLOGY.md in the repository.If you’d like to take a closer look, the code is on GitHub: https://github.com/yotambraun/APDTFlow. I hope you found this article helpful. If you know someone who might benefit from it, please feel free to pass it along, and if you enjoyed this post, please give it a clap. Feel free to follow me on Medium for more articles!APDTFlow v0.4.0: From a Critical Bug to Forecasting “When” was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.