Repository navigation
[AINode] Add Timestral as a built-in forecasting model, with weights provided by the user - #19272
kotselidis wants to merge 11 commits into
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Malformed metadata can still trigger inference-pool creation, combined-series attention can exhaust memory, and slow downloads block management operations and delay shutdown.
3 open issues
What changed in this PR
Adds Timestral-209M as an AINode built-in forecasting model. Its restricted-license weights are downloaded explicitly through LOAD MODEL, rather than automatically at startup.
Changes:
- Adds Timestral inference code and a median-forecast pipeline supporting multivariate inputs, covariates, and multi-block horizons.
- Introduces on-request downloads, model-state handling, and RPC checks for unavailable weights.
- Adds unit and integration coverage and updates third-party license notices.
| File | Description |
|---|---|
NOTICE |
Adds Timestral attribution. |
LICENSE |
Records the vendored code’s Apache license. |
iotdb-core/ainode/tests/test_timestral.py |
Tests checkpoint loading, forecasts, and covariates. |
iotdb-core/ainode/tests/test_builtin_model_download.py |
Tests download states, retries, and pre-download rejection. |
iotdb-core/ainode/src/assembly/resources/NOTICE-binary |
Adds attribution to AINode binary notices. |
iotdb-core/ainode/iotdb/ainode/core/rpc/handler.py |
Rejects inference before on-request weights are available. |
iotdb-core/ainode/iotdb/ainode/core/model/timestral/scaler.py |
Implements normalization and forecast rescaling. |
iotdb-core/ainode/iotdb/ainode/core/model/timestral/pipeline_timestral.py |
Adapts AINode inputs and returns median forecasts. |
iotdb-core/ainode/iotdb/ainode/core/model/timestral/modeling_timestral.py |
Integrates strict checkpoint loading and device transitions. |
iotdb-core/ainode/iotdb/ainode/core/model/timestral/model.py |
Implements the Timestral network and quantile prediction. |
iotdb-core/ainode/iotdb/ainode/core/model/timestral/masks.py |
Defines attention masks and temporal positions. |
iotdb-core/ainode/iotdb/ainode/core/model/timestral/layers.py |
Adds transformer layers and rotary embeddings. |
iotdb-core/ainode/iotdb/ainode/core/model/timestral/forecaster.py |
Handles block decoding, covariates, and forecast adjustments. |
iotdb-core/ainode/iotdb/ainode/core/model/timestral/covariate_encoding.py |
Encodes categorical covariates numerically. |
iotdb-core/ainode/iotdb/ainode/core/model/timestral/config.py |
Defines and validates checkpoint configuration. |
iotdb-core/ainode/iotdb/ainode/core/model/timestral/__init__.py |
Adds the package initializer and attribution. |
iotdb-core/ainode/iotdb/ainode/core/model/model_storage.py |
Manages deferred downloads and stored-model states. |
iotdb-core/ainode/iotdb/ainode/core/model/model_info.py |
Registers Timestral and adds the startup-download flag. |
iotdb-core/ainode/iotdb/ainode/core/manager/model_manager.py |
Exposes built-in model downloads to callers. |
iotdb-core/ainode/iotdb/ainode/core/inference/pool_controller.py |
Downloads deferred weights before loading inference pools. |
integration-test/src/test/java/org/apache/iotdb/ainode/utils/AINodeTestUtils.java |
Defines expected on-request built-in models. |
integration-test/src/test/java/org/apache/iotdb/ainode/it/AINodeSharedClusterIT.java |
Covers model listing and load/inference/forecast flow. |
Review effort: Balanced
CRZbulabula
left a comment
There was a problem hiding this comment.
Reviewed e3475fa. I independently reproduced the three issues in the existing review threads and added the evidence there: synchronous downloads block the shared controller, failed configuration processing still reports download success, and batching independent series causes quadratic mask-memory growth across requests. These should be addressed before merging.
All ten new Python tests pass locally (six model tests and four download tests), using Python 3.11 / PyTorch 2.11.0 on CPU. This does not validate the pinned PyTorch 2.14.1 or GPU behavior. The current AINode CI job is green, but its explicit Python test commands only select test_dependency_security.py and test_sundial_flow_loss.py; please include both new regression suites in CI as well.
I replied separately in #19270 about the optional download design and the remaining weights-license question.
CRZbulabula
left a comment
There was a problem hiding this comment.
Thanks for the follow-up commits. The malformed-config result and unbounded cross-request batching issues are fixed, and the new test suites now run in CI. All 15 new Python tests and the 19 packaged integration tests pass in the latest AINode job.
Besides the pending-load/unload issue noted in the lifecycle thread, the weights-license question remains open. The restriction is documented in the PR description, but there are still no user-facing setup instructions explaining the eligibility condition before LOAD MODEL downloads the weights. Please add those instructions with a link to the exact checkpoint license. We also need to close the maintainer/PMC assessment of this optional download workflow; an explicit download does not itself resolve the license restriction.
After #19273 lands, please rebase this PR: the two changes conflict in model_info.py and the license/notice files. Both model registrations and the max_output_length / download_on_start fields need to be retained and tested together.
| device_id_list (list[torch.device]): List of device_ids where the model should be loaded. | ||
| """ | ||
| with self._pending_loads_lock: | ||
| self._pending_loads.update((model_id, d) for d in device_id_list) |
There was a problem hiding this comment.
There is still a LOAD-to-UNLOAD ordering race here. load_model() publishes the pending counter, releases the lock, and only then enqueues the load. If another request runs in that gap, InferenceManager.unload_model() sees is_loading() == True and enqueues unload first; the worker finds no pool and drops it, then the load proceeds and leaves the model loaded. Please make publishing the pending state and enqueueing the load atomic (or otherwise preserve FIFO ordering), and add an event-controlled test through InferenceManager that forces this interleaving.
There was a problem hiding this comment.
Fixed in d04aa5d: load_model() now publishes the pending load and puts it on the task queue inside the same _pending_loads_lock block, so an unload_model() that sees is_loading() == True is always queued after the load (FIFO on the controller's queue). The new test_unload_racing_a_load_through_inference_manager_runs_after_it in test_builtin_model_load.py forces the interleaving through InferenceManager: the queue holds the load's put() open, UNLOAD MODEL is issued in that gap, and the test checks that it cannot overtake and that the controller runs the load before the unload. It fails on the previous commit and passes now.
There was a problem hiding this comment.
Also fixed the mirror case in c177c9b: a LOAD MODEL issued while an UNLOAD MODEL is still queued used to be skipped, because the pool was still listed, and the unload then left the model unloaded. Unloads are now tracked as pending in the same way (published and queued in one step under the lock), and InferenceManager.load_model() no longer counts pools that a pending unload is about to remove, so the load is queued after the unload. test_load_after_a_pending_unload_through_inference_manager_runs_after_it covers it; it fails before this commit.
| if self._pool_controller.has_request_pools( | ||
| model_id=existing_model_id, device_id=device_id | ||
| ): | ||
| ) and not self._pool_controller.is_unloading(existing_model_id, device_id): |
There was a problem hiding this comment.
The new pending counters close the queue-insertion races, but the manager's state check and forwarding call are still separate. For example, with an existing pool, LOAD can observe has_request_pools=True and is_unloading=False, then pause before returning; a concurrent UNLOAD can enqueue and remove the pool, while the LOAD is skipped, leaving the model unloaded even though LOAD arrived during the operation. The inverse window exists between UNLOAD's checks at lines 124-126 and its call to PoolController.unload_model(): a later LOAD can observe the pool and no pending unload, skip enqueueing, then the unload removes it. Could you make the state decision and enqueue one serialized controller operation (or add event-controlled tests for both check-to-forward interleavings)?
There was a problem hiding this comment.
Fixed in efb62dc by making the decision and the enqueue one serialised controller operation, as you suggested.
PoolController.request_load() and request_unload() each run as one block under _pending_lock:
- They read the pools and the pending loads and unloads.
- They pick the devices that need the work: a LOAD goes to a device with no pool, or one that a pending unload is about to clear; an UNLOAD goes to a device with a pool, or with a load still pending.
- They mark that work pending and put it on the task queue.
InferenceManager.load_model() and unload_model() now only call these methods and report the devices they return, so no check is left outside the lock.
Requests are therefore serialised in the order they take the lock, and each one sees every earlier request. If the earlier request's task has already run, its effect is in the pools; if not, it is still marked pending, because a task clears its pending mark only after it has changed the pools.
Two event-controlled tests through InferenceManager cover the check-to-forward interleavings. In each, the first request is held inside its pool check while the second is issued.
- UNLOAD during a LOAD's check: the UNLOAD cannot complete while the LOAD is held. Afterwards the outcome is that of LOAD then UNLOAD: the load is skipped, then the model is unloaded.
- LOAD during an UNLOAD's check: the LOAD waits, then sees the pending unload and queues itself after it. The model ends up loaded.
Both tests fail on the previous commit and pass now; test_builtin_model_load.py passes all 10 tests, in five consecutive runs.
|
I checked the published ASF optional-feature guidance and the checkpoint license. To keep the weights entirely user-provided and out of IoTDB distribution/download flows, please revise this PR along these lines:
This follows the ASF policy path for an optional feature that relies on non-included work more directly. The public policy text does not specifically address model checkpoints, so this change is intended to ensure the weights are obtained and installed independently by each user. |
efb62dc to
a4ad922
Compare
|
Thanks for checking the ASF guidance. This PR is now revised along those lines, rebased onto the current
Every new check is gated on The title and description are updated to match. The workflows on the new head will need a maintainer's approval to run. |


Description
This PR adds Timestral (Mistral AI) to AINode's built-in forecasting models, next to
timer_xl,sundial,chronos2,moirai2,totoandmoment. Timestral is a patch-based transformer for multivariate probabilistic forecasting. It forecasts 21 quantiles (0.01 to 0.99) from a context of up to 32,768 steps, and it can use past-only and future-known covariates. The model is registered astimestral, with the weights ofmistralai/Timestral-209M. The 209M model is the largest of the four published sizes (5M, 28M, 123M, 209M) and the one Timestral's own documentation uses.Unlike the other built-in models, AINode neither includes nor downloads Timestral's weights. Each user obtains the checkpoint independently and places its files in AINode's model directory;
timestralstays inactive until then. The reason is the weights' licence, below.Weights licence
Timestral's code is under the Apache License 2.0. Its weights are not. Every published size is under a "Modified MIT" licence (licence text), whose second condition reads:
IoTDB's source and binary distributions do not include the weights, and AINode never fetches, mirrors or proxies them: not at startup, and not on
LOAD MODEL. Users who install them obtain them themselves and must have the right to use them. The Apache-2.0 attribution inLICENSEandNOTICEcovers the adapted code only, and says so.Usage
FORECASTandCALL INFERENCEontimestralfail in the same way, with error 1504. After the user has placedconfig.json,model.safetensorsandLICENSEof the checkpoint in that directory:The model is active from the next start on, as long as the files stay in place.
iotdb-core/ainode/README.mdhas the setup instructions for users: the checkpoint, the three files, the directory, and the licence's revenue condition.Example: the input is 1024 points of
50 + 10·sin(2πt/24) + 0.01·t. The request is aTForecastReqwithoutputLength = 24, sent to AINode's inference manager on CPU with the Timestral-209M checkpoint. The response is 24 values (the median forecast). The first six:The mean absolute error is 0.031 over 24 steps and 0.049 over 96 steps.
Built-in models with user-provided weights
ModelInfogets an optionaluser_provided_weights, the text that tells users where to obtain the weights and under which licence. Onlytimestralsets it. For every other model it isNone, and their discovery, download at startup, loading and forecasts are unchanged.ModelStorageregisters such a model without any download: it isactiveifconfig.json,model.safetensorsandLICENSEare in<ain_models_dir>/builtin/timestral/and readable (config.jsonparses,model.safetensorshas a safetensors header), andinactiveotherwise.LOAD MODELchecks the files again withModelStorage.validate_user_provided_model, so files placed after startup are found. If they are missing or unreadable, it returns error 1509 with the message shown above, naming the problem, the directory and the licence, and nothing is queued.FORECASTandCALL INFERENCEon an inactive model of this kind do the same check and return error 1504 with that message.TimestralForPrediction.from_pretrainedloads only from an existing local directory, withlocal_files_only=True, so the loader cannot fall back to the Hugging Face Hub.Ordering of LOAD and UNLOAD MODEL
LOAD MODELandUNLOAD MODELdecide which devices need work, mark that work pending and queue it in one step under a lock in the pool controller (PoolController.request_loadandrequest_unload). Before,InferenceManagerchecked the pools and queued the task separately, so anUNLOAD MODELright after aLOAD MODELcould be skipped because the pool did not exist yet, and aLOAD MODELright after anUNLOAD MODELcould be skipped because the pool still existed. Requests are now applied in the order they take the lock. This part applies to all models.Model code
iotdb/ainode/core/model/timestral/contains the inference code from mistralai/timestral 1.0.0 (Apache License 2.0), in the same way aschronos2/contains the code from chronos-forecasting. The model, forecaster, layers, masks, scaler, covariate encoding and configuration are unchanged except for these points:iotdb.ainode.core.model.timestralpackage, and files carry the ASF header followed by Mistral AI's copyright notice.loading.py) andTimestralForecaster.from_pretrainedare left out. AINode loads the checkpoint only from the local model directory.AINode integration
modeling_timestral.TimestralForPredictionis the model, loaded throughPyTorchModelHubMixin(hub_mixin_clsinModelInfo), a loading path AINode already supports.config.jsonis read into Timestral's ownTimestralConfig, which rejects unknown keys. The weights load withstrict=True. The rotary-embedding frequencies are recomputed whenever the model is moved to a device, as Timestral's own loader does after moving the model.pipeline_timestral.TimestralPipelineruns Timestral'sTimestralForecasterwith its default settings:past_covariatesbecomes a past covariate. A covariate that also appears infuture_covariatesbecomes a known covariate, built from its past and future values.output_lengththat AINode accepts (up to 2880) works.Dependencies
There are no new dependencies. Timestral needs only PyTorch, NumPy, safetensors and huggingface_hub, which AINode already pins.
pyproject.toml,ainode.specandainode.xmlare unchanged.ainode.specalready collects every module underiotdb.ainode.core.Licences
The code is under the Apache License 2.0 (licence). This PR adds it to
LICENSE,NOTICEand AINode'sNOTICE-binary. See the note above about the licence of the weights.Tests
tests/test_timestral.py(unittest, CPU only, no downloads) uses a two-layer Timestral with random weights. The tests:TimestralPipeline, and check the output shapes for 1-D and 2-D targets over more than one decode block, and that the result is the forecaster's median;tests/test_timestral_local_files.py(unittest; no network: socket connections andhf_hub_downloadfail the test) checks that:inactiveat startup without its files and is never downloaded, while the other built-in models still go through their download at startup;config.jsonthat cannot be read and a file that is not a safetensors file give the setup message, naming the files, the directory, the checkpoint and the revenue condition;LOAD MODEL's check, loads through AINode's loader and forecasts, and isactiveat the next startup;LOAD MODELand forecasts are rejected without the files and pass with them, while other models are not checked at all.tests/test_builtin_model_load.py(unittest) checks the ordering throughInferenceManager: anUNLOAD MODELright after aLOAD MODELruns after it, aLOAD MODELafter a pendingUNLOAD MODELis queued after it, and a request issued while another is between its check and its queueing waits for it. Each of these fails on the code before the change.test_dependency_security.pyandtest_sundial_flow_loss.py. None of them downloads a checkpoint.AINodeTestUtils.USER_PROVIDED_BUILTIN_MODEL_MAPliststimestralasinactive. TheSHOW MODELStest checks that state, and the newuserProvidedBuiltInModelNotInstalledTestchecks thatLOAD MODEL timestralandFORECASTfail with the setup message, so CI never downloads the real checkpoint.This PR has:
for an unfamiliar reader.
for code coverage.
Key changed/added classes (or packages if there are too many classes) in this PR
iotdb/ainode/core/model/timestral/(new): the Timestral model and forecaster,TimestralForPrediction,TimestralPipelineiotdb/ainode/core/model/model_info.py:ModelInfo.user_provided_weights;timestralentry inBUILTIN_HF_TRANSFORMERS_MODEL_MAPiotdb/ainode/core/model/model_storage.py: such a model is never downloaded;validate_user_provided_modelchecks its local filesiotdb/ainode/core/rpc/handler.py:LOAD MODELand forecasts on such a model without its files return the setup messageiotdb/ainode/core/inference/pool_controller.py,iotdb/ainode/core/manager/inference_manager.py:LOAD MODELandUNLOAD MODELare decided and queued in one stepiotdb-core/ainode/README.md: setup instructions for Timestral's weightsiotdb-core/ainode/tests/test_timestral.py,tests/test_timestral_local_files.py,tests/test_builtin_model_load.py(new).github/workflows/cluster-it-1c1d1a.yml: runs the new test filesintegration-test/.../ainode/utils/AINodeTestUtils.java,.../it/AINodeSharedClusterIT.java:USER_PROVIDED_BUILTIN_MODEL_MAPand its testsLICENSE,NOTICE,iotdb-core/ainode/src/assembly/resources/NOTICE-binary