Skip to content

Speed up large Agent iterate_forecast runs (AB#89835) - #305

Open
Mike Tokic (mitokic) wants to merge 3 commits into
mainfrom
mitokic/11162026/run-speed-ups
Open

Mike Tokic (mitokic) wants to merge 3 commits into
mainfrom
mitokic/11162026/run-speed-ups

Conversation

@mitokic

Copy link
Copy Markdown
Collaborator

This pull request introduces significant performance improvements and bug fixes to the finnts package, particularly for large-scale and Spark-based workflows. The changes focus on batching work for efficiency, reducing redundant computation and I/O, and improving robustness in parallel and distributed processing. There are also several targeted bug fixes and dependency updates.

Key changes include:

Performance and Scalability Improvements

  • On Spark, the EDA, best-model selection, and model summary stages now process several series per task instead of one, reducing task startup overhead and improving speed for large runs (spark_stage_batches() batching in R/agent_eda.R and R/agent_summarize_models.R). [1] [2] [3] [4] [5] [6]
  • Summarizing models for global runs is now done once per run and shared across all relevant series, avoiding redundant computation and ensuring consistency (global summary caching and sharing in summarize_models). [1] [2] [3] [4]

Dependency and Configuration Updates

  • Added yardstick as a direct dependency in DESCRIPTION to support RMSE-only tuning and back-testing, and incremented the package version. [1] [2]

Documentation and Logging

  • Updated documentation in code and NEWS.md to reflect the new batching behavior and performance improvements, and to clarify how Spark tasks are now grouped and processed. [1] [2] [3]

Bug Fixes

  • Multiple bug fixes in data cleaning, run metadata, and Spark task management to improve reliability and correctness, especially in edge cases with missing values, run interruptions, and process crashes.

Minor Improvements

  • CSV file reading/writing with vroom is now more efficient on many-core machines, and logging/listing of run logs and series names is optimized to reduce unnecessary I/O.

These changes together make the package faster, more robust, and more scalable for large forecasting projects, especially when using Spark or handling many time series.

Cuts the restart, I/O and training overhead found in an 8,205-series
PROD run that took 43 hours, without changing forecasts or model choice.

- Survive per-series R crashes on Spark and local_machine: each series
  runs in its own process and is retried from its completed iterations.
- Keep large driver objects out of Spark task closures, and make
  re-run series tasks return without repeating finished work.
- Resume a global iteration cut off after training instead of retraining.
- List run logs and inputs once per start, read known artifacts by exact
  path, and parallelize best-run logging and finalization reads.
- Read small CSVs with fewer vroom threads.
- Train faster with identical results: vectorized undifferencing, no
  xgboost training-set evaluation on discarded fits, RMSE-only tuning,
  and one validation fit for models without hyperparameters.
- Summarize each global model once per run, and run several series per
  Spark task in the EDA, selection and summary stages.

Saved data changes (approved): best-run metadata keeps every series'
settings as written, and chronos2 permutation importance for
global-winner series is one shared draw per global run.

Also fixes prep_data() failing to interpolate series with fewer than two
observed values when outlier and missing-value cleaning are both on.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The discarded-fit path removes evaluation datasets required for early stopping, so tuning and back-test fits with stop_iter or early_stop enabled can fail instead of matching retained fits.

1 open issue
What changed in this PR

This PR improves large FinnTS Agent forecasting runs by reducing Spark task overhead, repeated computation, and artifact I/O, while adding recovery for interrupted work and crashed series processes.

Changes:

  • Batch short Spark stages, share global model summaries, and streamline artifact reads and writes.
  • Optimize training and undifferencing, resume interrupted global iterations, and isolate per-series crashes.
  • Add regression coverage, update parallel-processing guidance, and declare yardstick as a direct dependency.
File Description
vignettes/​parallel-processing.Rmd Documents process isolation and crash retries.
vignettes/​ai-agent.Rmd Explains interrupted global-iteration recovery.
tests/​testthat/​test-undifference.R Checks vectorized reconstruction and fallback equivalence.
tests/​testthat/​test-train-models-speedups.R Checks training, refit, and worker equivalence.
tests/​testthat/​test-summarize_models.R Tests shared global summaries on local workers.
tests/​testthat/​test-spark-stage-batches.R Tests batching and stage-output equivalence.
tests/​testthat/​test-series-isolation.R Covers crash detection, retries, and error propagation.
tests/​testthat/​test-read-write-data.R Tests adaptive CSV thread counts.
tests/​testthat/​test-prep_data.R Covers cleaning sparse series.
tests/​testthat/​test-multistep.R Tests discarded-fit optimization and trainer fallback.
tests/​testthat/​test-finalize_run.R Checks pooled finalization equivalence.
tests/​testthat/​test-final-models-restart.R Updates restart mocks for saved metadata.
tests/​testthat/​test-driver-artifact-lookups.R Covers reduced listings and preserved retry history.
tests/​testthat/​test-artifact-io-parallel.R Tests finalization with installed worker processes.
tests/​testthat/​test-agent-update-forecast.R Covers lean dispatch and completed-update reuse.
tests/​testthat/​test-agent-selection-policy.R Tests pooled promotion and write failures.
tests/​testthat/​test-agent-global-resume.R Checks unfinished-series routing and lean dispatch.
tests/​testthat/​test-agent-global-iteration-resume.R Covers resuming trained, unrecorded global iterations.
tests/​testthat/​test-agent-forecast-selection.R Tests snapshot-based and pooled forecast reads.
tests/​testthat/​test-agent-custom-update-workers.R Adapts custom-update checks to isolated processes.
tests/​testthat/​test-agent-custom-iteration-workers.R Adapts custom-iteration checks to isolated processes.
tests/​testthat/​test-agent-artifact-reads.R Covers metadata fidelity and shared artifact reads.
tests/​testthat/​helper-update-chain.R Passes saved metadata into forecast loading.
tests/​testthat/​helper-artifact-io.R Adds reusable local and global summary fixtures.
skills/​finn/​version.json Records the skill release and crash-recovery guidance.
skills/​finn/​tests/​test_skill.R Checks memory-related crash classification.
skills/​finn/​scripts/​finn_common.R Updates the skill version constant.
skills/​finn/​references/​parallelism.md Explains isolated workers and memory-failure recovery.
R/​train_models.R Streamlines validation, metrics, and undifferencing.
R/​series_isolation.R Adds isolated series execution and crash retries.
R/​read_write_data.R Optimizes CSV threading, type inference, and lookups.
R/​prep_data.R Guards imputation for insufficient observations.
R/​parallel_util.R Adds Spark batching and artifact I/O pools.
R/​multistep_xgboost.R Adds evaluation-free training for discarded fits.
R/​final_models.R Batches Spark model-selection tasks.
R/​agent_update_forecast.R Adds lean isolated dispatch and snapshot-based reconciliation.
R/​agent_summarize_models.R Shares global summaries and batches Spark jobs.
R/​agent_eda.R Batches per-series Spark EDA work.
NEWS.md Records performance improvements and reliability fixes.
DESCRIPTION Bumps the development version and adds yardstick.

Review effort: Balanced

Comment thread R/multistep_xgboost.R Resolved
Thrown-away multistep xgboost fits skip xgboost's training-set
evaluation, but early stopping needs evaluation data, so such fits now
use modeltime's trainer. finnts runs never set early stopping, so their
results are unchanged. Addresses PR #305 review.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Spark fork isolation and mounted-storage parallel publication require runtime validation of native-library safety, crash recovery, and cross-node artifact visibility that this review environment cannot provide.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@mitokic

Copy link
Copy Markdown
Collaborator Author

Runtime check on a Synapse DEV Spark pool: fork isolation (P4) and parallel writes to mounted storage (P3)

This answers the review's request for runtime checks of native-library safety, crash recovery and cross-node visibility. It's a free check (no LLM calls) on the DEV Synapse pool.

Setup

  • R 4.4.1, sparklyr 1.8.6, Spark 3.5 on YARN, threaded OpenBLAS 0.3.29.
  • 2 executors × 2 cores, with ADLS mounted at /synfs.
  • The branch build from 56ececa7 (0.7.0.9024) ran everywhere: on the driver, its PSOCK workers, the executors, the forked children and their inner pools. Each process reported the version it loaded.
  • Scratch folders were removed and the Livy sessions deleted afterwards.

P4: each series in a forked child on the executors

Eight series went through run_series_tasks(parallel_processing = "spark"). Each one ran the full local workflow inside its forked child:

  • prep_data(multistep_horizon = TRUE), then prep_models, train_models and final_models
  • arima, ets, prophet (rstan), multistep xgboost (OpenMP) and multistep glmnet
  • all stages on one shared inner PSOCK pool inside the child

Two series crashed on their first attempt only:

  • S03 sent itself SIGSEGV after prep_models, so R's crash handler ran.
  • S06 was SIGKILLed after train_models while its inner pool was still running. This stands in for the out-of-memory killer.
Check Result
Job finishes without aborting the Spark stage ✅ all 8 series returned in 295 s, running on both executor nodes
Crashes are named and retried ✅ Series 'S03' crashed (Creating Train Test Splits): R reported: *** caught segfault *** … Retrying (attempt 2 of 4)
✅ Series 'S06' crashed (Training Individual Models): killed by the operating system, likely out of memory. Retrying (attempt 2 of 4)
Retries resume from saved artifacts ✅ S06's retry skipped training and reused the models saved before the kill
Forecasts match a sequential, in-process run ✅ identical() for all 8 series, including both crashed ones (66 rows each)
Native libraries and inner PSOCK pools work inside forked children ✅ xgboost/OpenMP, rstan, glmnet, OpenBLAS and vroom all ran there. Every inner worker loaded the branch
Nothing left behind on executor nodes (/proc scan of both nodes) ✅ no PSOCK workers, no zombies, and the killed child's 2 inner workers were gone

The parent R worker only loads packages and forks; model code runs only in the child. Libraries that start worker threads on first use, such as xgboost's OpenMP, therefore start them after the fork.

P3: pooled best-run publication on /synfs (500 global series)

These are the branch's real per-series tasks: write_agent_best_run_record, check_agent_best_run_record, read_agent_best_run_records and finalize_run(). Each was run with the series I/O pool and again in-process, which is how main does it.

Step (500 series) Pooled (10 workers) In-process
Write 4.0 s 15.1 s
Read-back check 0.9 s 4.9 s
Bulk read 0.7 s 5.2 s
finalize_run() 15.8 s 28.0 s
  • The saved files are byte-identical (md5) between the two modes.
  • The branch's read-back check passed for all 500 records.
  • Cross-node reads:
    • Before finalization, executors on the driver's node and on another node read all 500 records correctly.
    • After finalize_run() rewrote them on the driver, executors that had already cached the old copies took time to see the new content: 376/500 immediately, 489 at 45 s and 500/500 within 60 s.

That delay comes from the mount's per-node cache, not from this PR. main rewrites the same files from the same driver node in a sequential loop.

The executor-side completion checks this PR adds only read a record to skip work that is already finished. An older copy always shows less progress, so a delayed read can lead to re-checking finished work, never to skipping unfinished work. When finished work is re-checked, the existing restart checks reuse the saved outputs.

Allow yardstick, now a declared import, in custom model package declarations. Split this branch's NEWS bullets to at most 20 words. Update custom Agent tests for the one-split validation check and the new completion check: the interrupted-update tests now move the best-run record aside instead of mocking its read, so the record is genuinely missing and is rebuilt without refitting.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants