Skip to content

[AINode] Improve inference correctness, concurrency, and worker recovery - #19520

Open
yunbow30944 wants to merge 4 commits into
apache:masterfrom
yunbow30944:ainode-oss-pr-no-covariates
Open

yunbow30944 wants to merge 4 commits into
apache:masterfrom
yunbow30944:ainode-oss-pr-no-covariates

Conversation

@yunbow30944

Copy link
Copy Markdown
Contributor

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 FORECAST accepts multiple independent target columns when the model supports them. Forecast results continue to use DOUBLE values 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, table CLASSIFY, and tree FORECAST now 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 of 3, the previous implementation kept the last three arrivals [3, 2, 1] and sent [1, 2, 3] after sorting; LatestTimeWindow now 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 by dn_ainode_max_input_length (default 2880, positive integer, warning logged on truncation; set consistently across DataNodes and restart to apply). Table CLASSIFY keeps labels aligned with selected values and reads its handle type ID as a single byte matching serialization.

Table FORECAST offloads blocking AINode RPC waits to a bounded dedicated executor so query execution threads remain free to schedule other operators. Integration uses an optional AsyncTableFunctionDataProcessor contract in TableFunctionOperator, leaving other TVFs, table CLASSIFY, and tree FORECAST on their existing synchronous paths. Table FORECAST propagates 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/UNLOAD placement 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 failed LOAD releases only its own still-owned device reservation once cleanup completes (preserving successful devices in multi-device loads and newer queued commands), and a no-op UNLOAD on 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 32 requests and 65536 total 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 with predict_batches_jointly=true run 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=0 by default, 1..8 opt-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. Optional AINODE_INPUT_CODEC (NumPy input decoding) and AINODE_REQUEST_IPC=numpy (standalone array copies for supported CPU tensors up to 256 KiB, defaulting to torch and falling back to torch for 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, and AINODE_RESULT_CODEC=pandas selects the legacy path explicitly. AINODE_RESULT_FORMAT remains independent and defaults to tensor. Forecast and inference RPC results continue using DOUBLE wire output per master. 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_OPTIONS propagate through preprocessing, execution, and postprocessing. revin and predict_batches_jointly use strict boolean parsing (booleans or case-insensitive true/false strings). 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_samples and samples_per_batch with None preserved), 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, while NaN values 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 and TRITON_F32_DEFAULT to be ieee. It wraps the original model's forward, including calls from generate. A custom worker uses prepare_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 separate dn_thrift_max_frame_size setting.

Property / Env Variable Default Scope and Bounds
AINODE_RESULT_CODEC / AINODE_RESULT_FORMAT numpy / tensor Bulk numeric column codec (pandas fallback); independent output format
AINODE_FRONTEND_PROCESSES 0 (off) Explicit 1..8 for shared-backend CPU RPC frontends
AINODE_INPUT_CODEC / AINODE_REQUEST_IPC off / torch Opt-in NumPy input decode; opt-in numpy IPC (≤ 256 KiB CPU tensors)
AINODE_FP32_EXECUTION Unset (off) compile requires TRITON_F32_DEFAULT=ieee and explicit prepare_calls()
dn_ainode_max_input_length / ain_inference_max_output_length 2880 / 2880 Positive integers; DataNode window cap / AINode output length cap
ain_inference_batch_max_requests / ain_inference_batch_input_points 32 / 65536 Positive integers; FIFO batch request and input-point caps
ain_rpc_max_concurrent_client_num / ain_inference_max_inflight 256 / 256 Positive integers; concurrent RPC connections and physical in-flight cap
ain_inference_timeout_ms / ain_inference_timeout_grace_ms 60000 / 5000 Positive integers (ms); inference timeout and worker teardown grace
ain_rpc_max_frame_size / ain_config_node_max_frame_size 16384000 / 16384000 Positive bytes ≤ 1073741823; independent of dn_thrift_max_frame_size

Tests

  • All 24 targeted Java tests passed across six test classes. These cover input windowing, forecast-handle compatibility, asynchronous table-function completion, cancellation and RPC handling, and configuration. The English and Chinese DataNode message classes compile on the rebased source.
  • 56 targeted AINode CPU tests passed after rebasing onto the base that includes TiRex-2. The tests confirm that both frontend modes reject a TiRex-2 output length of 400 before dispatch and accept a subsequent request of length 24. They also cover frontend restart, TLS, compact RPC, and model worker recovery.
  • On the preceding base, the broader regression passed 108 AINode CPU tests, 20 CUDA FP32 tests, and six Python SDK tests on Python 3.11 with PyTorch 2.14.1+cu126, Transformers 4.56.2, and Thrift 0.25.0. It included large-frame RPC round trips with both binary and compact protocols. These counts include overlapping coverage with the targeted reruns.
  • AINode Black and isort, client Black, Java Spotless, and Checkstyle passed.

This PR has:

  • been self-reviewed.
  • added documentation for new or modified features or behaviors.
  • added unit tests or modified existing tests to cover new code paths.

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).

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.
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.

1 participant