Repository navigation
[AINode] Improve inference correctness, concurrency, and worker recovery - #19520
Open
yunbow30944 wants to merge 4 commits into
Open
yunbow30944 wants to merge 4 commits into
yunbow30944 wants to merge 4 commits into
Conversation
Select input windows by latest timestamp, support asynchronous table FORECAST completion, and keep inference capacity occupied until physical work finishes. Add compatible request batching, bounded worker-pool recovery, optional shared-model CPU frontends, numeric column encoding, and an opt-in prepared FP32 execution backend. Preserve the existing FORECAST handle and Thrift field definitions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
This PR fixes input-window selection for out-of-order data and improves how Apache IoTDB schedules, serves, and recovers AINode inference requests. Table
FORECASTaccepts multiple independent target columns when the model supports them. Forecast results continue to useDOUBLEvalues in the existing RPC format.Numeric result encoding uses bulk column operations by default. Additional CPU frontend processes, NumPy input decoding, NumPy transfer between processes, and strict FP32 compilation are opt-in.
DataNode Input Windowing and Async Table FORECAST
Table
FORECAST, tableCLASSIFY, and treeFORECASTnow retain the latest bounded input window by timestamp and send retained rows in ascending timestamp order. Previously, all three entry points evicted the earliest-arriving rows (removeFirst()) before sorting, which dropped newer points whenever inputs arrived out of order. For example, given arrival timestamps[5, 4, 3, 2, 1]and a window of3, the previous implementation kept the last three arrivals[3, 2, 1]and sent[1, 2, 3]after sorting;LatestTimeWindownow retains the three latest timestamps and sends[3, 4, 5]. When duplicate timestamps fall on the cutoff boundary, later arrivals are retained first and retained duplicates preserve their arrival order. Input preservation (PRESERVE_INPUT/keep input) continues returning all original rows. The window cap is configured bydn_ainode_max_input_length(default2880, positive integer, warning logged on truncation; set consistently across DataNodes and restart to apply). TableCLASSIFYkeeps labels aligned with selected values and reads its handle type ID as a single byte matching serialization.Table
FORECASToffloads blocking AINode RPC waits to a bounded dedicated executor so query execution threads remain free to schedule other operators. Integration uses an optionalAsyncTableFunctionDataProcessorcontract inTableFunctionOperator, leaving other TVFs, tableCLASSIFY, and treeFORECASTon their existing synchronous paths. TableFORECASTpropagates the remaining query deadline to the RPC call, closes and invalidates the active connection on query cancellation, never auto-retries failed inference calls, and restores borrowed connection timeouts after a successful call.AINode Concurrency, Batching, Lifecycle, and Fault Recovery
AINode enforces bounded RPC connections and physical in-flight admission, releasing capacity only when physical execution finishes or worker exit is confirmed. Fixed-interval polling in waiting paths is replaced by condition-variable and queue notifications. Because a caller timeout does not stop an executing model, physical capacity is never returned early and is released exactly once upon actual completion or confirmed exit of the old worker process; queued requests whose deadlines expire before dispatch are dropped without entering the model. Unloaded CPU fallback uses a single concurrency slot and runs each admitted call on a daemon thread, preserving physical capacity accounting until completion without allowing a stuck fallback call to block process shutdown.
On unexpected worker exit or half-frame result-channel corruption, AINode executes a fenced teardown-and-rebuild recovery sequence within a bounded retry budget. Recovery pauses new inference and model-management requests, fences the old runtime, waits for confirmed exit of old worker processes and result receivers, fails pending requests without automatic replay, replaces IPC channels, restores accepted
LOAD/UNLOADplacement intent (preserving one model worker per device), and resumes traffic after readiness probes pass. If cleanup or reload cannot be confirmed or retries are exhausted, inference remains unavailable until restart. Ordinary model-option errors remain per-request errors and do not trigger recovery. A failedLOADreleases only its own still-owned device reservation once cleanup completes (preserving successful devices in multi-device loads and newer queued commands), and a no-opUNLOADon a never-loaded model leaves its management state intact so CPU fallback stays available.The batcher collects ready requests in arrival order and runs compatible requests together. The default budget is
32requests and65536total target input points. Requests are grouped by target count, input length, output length, and model options. Requests that would exceed the current batch budget stay for the next batch, and a single over-budget request executes alone. Requests withpredict_batches_jointly=truerun in their own group. Batch outputs transfer to CPU before splitting into individual responses.Data Path, Codecs, and Model Options
Optional shared-backend CPU RPC frontends (
AINODE_FRONTEND_PROCESSES=0by default,1..8opt-in) parallelize request decoding, pure-target input preparation, and response encoding without duplicating loaded models. Frontend shutdown serializes cleanup, escalates surviving children through terminate and kill with rejoins, and confirms process exit before dropping handles. OptionalAINODE_INPUT_CODEC(NumPy input decoding) andAINODE_REQUEST_IPC=numpy(standalone array copies for supported CPU tensors up to256 KiB, defaulting totorchand falling back totorchfor larger or unsupported tensors) are opt-in.Bulk column numeric result encoding (
AINODE_RESULT_CODEC=numpy) is enabled by default for supported 2D numeric matrices (bool,int32,int64,float32,float64), producing wire-equivalent TsBlock column bytes. Unsupported shapes or dtypes fall back to the legacy encoder, andAINODE_RESULT_CODEC=pandasselects the legacy path explicitly.AINODE_RESULT_FORMATremains independent and defaults totensor. Forecast and inference RPC results continue usingDOUBLEwire output permaster. The Python client SDK decodes timestamps using standard time types while preserving timezone semantics.Model options and input validation follow one contract across both CPU fallback and resident-model paths.
MODEL_OPTIONSpropagate through preprocessing, execution, and postprocessing.revinandpredict_batches_jointlyuse strict boolean parsing (booleans or case-insensitivetrue/falsestrings). Built-in pipelines parse wire-string numeric options at their owning boundaries (Chronos2:context_length,batch_size,max_output_patches;Sundial:num_samples;Toto:num_samplesandsamples_per_batchwithNonepreserved), while arbitrary option strings for registered pipelines pass through untouched. Before dispatch, both frontend modes require a positive output length within the configured limit and any model-specific limit. Empty targets and infinite values are rejected, whileNaNvalues are preserved for models supporting missing values.Optional Strict FP32 Backend
Custom integrations can opt into strict FP32 compilation with
AINODE_FP32_EXECUTION=compile. The backend uses the highest FP32 matrix multiplication precision, disables TF32, selects math-only scaled dot-product attention, and requires Triton's effective FP32 setting andTRITON_F32_DEFAULTto beieee. It wraps the original model'sforward, including calls fromgenerate. A custom worker usesprepare_calls()with representative inputs before serving. Preparation checks numerical results, random number generator state, and model state. The prepared execution applies to one forward signature, including its tensor shapes and scalar options. Standard workers and requests without a matching prepared signature use the original execution path.Defaults, Configuration, and Compatibility
The six new AINode serving limits (
ain_rpc_max_concurrent_client_num,ain_inference_max_inflight,ain_inference_timeout_ms,ain_inference_timeout_grace_ms,ain_inference_batch_max_requests,ain_inference_batch_input_points) fail fast during configuration loading when invalid, preventing later properties from being silently skipped. The AINode server and its ConfigNode client each apply their configured receive limit to both transport frames and Thrift string and binary fields. DataNode retains its separatedn_thrift_max_frame_sizesetting.AINODE_RESULT_CODEC/AINODE_RESULT_FORMATnumpy/tensorpandasfallback); independent output formatAINODE_FRONTEND_PROCESSES0(off)1..8for shared-backend CPU RPC frontendsAINODE_INPUT_CODEC/AINODE_REQUEST_IPCtorchnumpyIPC (≤256 KiBCPU tensors)AINODE_FP32_EXECUTIONcompilerequiresTRITON_F32_DEFAULT=ieeeand explicitprepare_calls()dn_ainode_max_input_length/ain_inference_max_output_length2880/2880ain_inference_batch_max_requests/ain_inference_batch_input_points32/65536ain_rpc_max_concurrent_client_num/ain_inference_max_inflight256/256ain_inference_timeout_ms/ain_inference_timeout_grace_ms60000/5000ain_rpc_max_frame_size/ain_config_node_max_frame_size16384000/163840001073741823; independent ofdn_thrift_max_frame_sizeTests
This PR has:
Key changed/added packages in this PR
iotdb-core/calc-commons(TableFunctionOperator,TableOperatorGenerator),iotdb-core/node-commons(AsyncTableFunctionDataProcessor,ITableFunctionAINodeService,LatestTimeWindow,ForecastTableFunction,ClassifyTableFunction,UDTFForecast,iotdb-system.properties.template,QueryMessages),iotdb-core/datanode(IoTDBConfig,IoTDBDescriptor,AINodeClient,DataNodeTableFunctionAINodeService,DataNodeMiscMessages, unit tests),iotdb-core/ainode(core.config,core.inference,core.manager,core.model,core.rpc,core.util,README.md,resources/conf, tests),iotdb-client/client-py(iotdb.utils).