Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 20 additions & 8 deletions iotdb-client/client-py/iotdb/utils/iotdb_rpc_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,24 @@
TIMESTAMP_STR = "Time"


def _timestamp_column_to_series(values, precision, timezone):
"""Convert an epoch column in bulk while retaining scalar edge semantics."""
if not values.dtype.isnative:
values = values.byteswap().view(values.dtype.newbyteorder("="))
try:
timestamps = pd.to_datetime(values, unit=precision, utc=True).tz_convert(
timezone
)
return pd.Series(timestamps, dtype=object)
except (ValueError, TypeError, OverflowError, KeyError, NotImplementedError):
# Wide timestamps and unsupported timezone cases follow the existing
# scalar conversion, including its original fallback/error behavior.
return pd.Series(
[convert_to_timestamp(value, precision, timezone) for value in values],
dtype=object,
)


class IoTDBRpcDataSet(object):

def __init__(
Expand Down Expand Up @@ -408,14 +426,8 @@ def _process_buffer(self):
data_array = np.array([x.decode("utf-8") for x in column_array])
# TIMESTAMP
elif data_type == 8:
data_array = pd.Series(
[
convert_to_timestamp(
x, self.__time_precision, self.__zone_id
)
for x in column_array
],
dtype=object,
data_array = _timestamp_column_to_series(
column_array, self.__time_precision, self.__zone_id
)
# DATE
elif data_type == 9:
Expand Down
91 changes: 91 additions & 0 deletions iotdb-core/ainode/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,94 @@ These source tests do not validate the packaged executable or GPU support.
The `Cluster IT - 1C1D1A` workflow builds and exercises the packaged AINode,
runs the Python tests, checks the Torch wheel's `sm_70` support, and executes a
CUDA tensor operation on the GPU runner.

## Input limits and serving defaults

Table `FORECAST`, table `CLASSIFY`, and tree `FORECAST` retain the latest input
rows by timestamp, up to `dn_ainode_max_input_length` in the DataNode
`iotdb-system.properties` file. The default is 2880 rows. Retained rows are
sent in ascending timestamp order; if the cutoff contains duplicate timestamps,
later arrivals are retained first and the retained duplicates keep their arrival
order. Input preservation still returns all original rows. Configure the same
positive limit on every DataNode and restart them after changing it.

The AINode `iotdb-ainode.properties` file exposes these independent limits:

| Property | Default | Purpose |
| --- | ---: | --- |
| `ain_inference_max_output_length` | 2880 | Maximum requested prediction length. The minimum is one step. |
| `ain_rpc_max_frame_size` | 16384000 | Maximum frame received by the AINode RPC server, in bytes. |
| `ain_config_node_max_frame_size` | 16384000 | Maximum frame received by the AINode ConfigNode client, in bytes. |

All limits must be positive integers; frame limits cannot exceed 1073741823.
Invalid configured limits fail startup. Raising a transport limit does not
increase model context length or the input/output limits. The DataNode receive
limit is separately controlled by `dn_thrift_max_frame_size`; size both ends for
the actual request and response and available memory.

Numeric result encoding is enabled by default through
`AINODE_RESULT_CODEC=numpy`. Supported numeric matrices use bulk column
encoding with the same wire values; other inputs keep the existing encoding
behavior. Set `AINODE_RESULT_CODEC=pandas` to select the legacy encoder.
`AINODE_RESULT_FORMAT` remains independent and defaults to Tensor results.

Additional RPC frontend processes remain disabled by default
(`AINODE_FRONTEND_PROCESSES=0`). Enable them explicitly for workloads that
benefit from parallel input preparation; they share the model pool rather than
loading a model copy per frontend. Table `FORECAST` accepts multiple target
columns when the model supports them. Options supplied through `MODEL_OPTIONS`
reach all pipeline stages in both unloaded CPU execution and loaded-model
execution. Timer-XL and Sundial accept `revin` as a Boolean or a case-insensitive
`true`/`false` string. Other values return an error.

If a model process exits unexpectedly or its result channel fails, AINode
temporarily rejects new inference and model-management requests while it retires
the old model pools. Once all old processes and result readers have exited,
pending requests fail and AINode rebuilds the models requested by accepted
`LOAD`/`UNLOAD` commands. Each device hosts one model worker. A `LOAD` on an
occupied device leaves its current model in place, including after recovery.
New requests use the replacement pools after their
readiness checks pass; failed requests are not replayed. Recovery has a bounded
retry budget. If cleanup or model loading cannot be confirmed, inference stays
unavailable and the service must be restarted. Ordinary model-option errors
remain request errors and do not trigger recovery.

## Optional FP32 execution backend

The PyTorch FP32 backend is off by default. Custom integrations can set
`AINODE_FP32_EXECUTION=compile` and `TRITON_F32_DEFAULT=ieee` before starting a
fresh, isolated CUDA model worker. Optimization requires both the environment
setting and Triton's effective FP32 setting to be `ieee`. Enabling the backend
sets process-wide float32 matmul precision to `highest`, disables TF32, and
selects math-only scaled dot-product attention. Use fresh, isolated compiler
cache directories to avoid artifacts built with other precision settings.

The standard AINode worker has no preparation hook. Setting the environment
variables alone leaves model calls on the original eager path. A custom
integration prepares its representative workload after loading the pipeline and
before accepting traffic. Put the model in evaluation mode and keep gradients
disabled throughout preparation.

```python
import torch

backend = getattr(pipeline.model, "_ainode_execution", None)
if backend is not None:
pipeline.model.eval()
with torch.no_grad(), backend.prepare_calls():
pipeline.forecast(real_inputs, **real_options)
preparation_stats = backend.snapshot()
```

Each model instance can prepare one forward signature, including tensor shapes
and scalar options. The slot holds either a successful
preparation or a recorded preparation failure. Other signatures, unsupported
devices or dtypes, and compiler guard misses use eager execution. Requests never
trigger new compilation.

Preparation runs the forward method multiple times and adds to startup time.
Use a side-effect-free workload. The backend preserves supported random number
generator states, rejects detectable Python mutations and hooks, and checks
parameters and buffers. If a probe changes tensor state, it restores the values
where possible and aborts preparation. `snapshot()` reports precision settings,
compiled segment executions, guard fallbacks, and rejection reasons.
117 changes: 116 additions & 1 deletion iotdb-core/ainode/iotdb/ainode/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ def __init__(self):
self._ain_target_config_node_list: TEndPoint = AINODE_TARGET_CONFIG_NODE_LIST
self._ain_rpc_address: str = AINODE_RPC_ADDRESS
self._ain_rpc_port: int = AINODE_RPC_PORT
self._ain_rpc_max_concurrent_client_num: int = 256
self._ain_rpc_max_frame_size: int = 16384000
self._ain_config_node_max_frame_size: int = 16384000
self._ain_inference_max_inflight: int = 256
self._ain_inference_timeout_ms: int = 60000
self._ain_inference_timeout_grace_ms: int = 5000
self._ain_inference_batch_max_requests: int = 32
self._ain_inference_batch_input_points: int = 65536
self._ain_cluster_ingress_address = AINODE_CLUSTER_INGRESS_ADDRESS
self._ain_cluster_ingress_port = AINODE_CLUSTER_INGRESS_PORT
self._ain_cluster_ingress_username = AINODE_CLUSTER_INGRESS_USERNAME
Expand Down Expand Up @@ -142,9 +150,75 @@ def get_ain_rpc_address(self) -> str:
def set_ain_rpc_address(self, ain_rpc_address: str) -> None:
self._ain_rpc_address = ain_rpc_address

def get_ain_inference_max_inflight(self) -> int:
return self._ain_inference_max_inflight

def set_ain_inference_max_inflight(self, value: int) -> None:
if value <= 0:
raise ValueError("ain_inference_max_inflight must be positive")
self._ain_inference_max_inflight = value

def get_ain_inference_timeout_ms(self) -> int:
return self._ain_inference_timeout_ms

def set_ain_inference_timeout_ms(self, value: int) -> None:
if value <= 0:
raise ValueError("ain_inference_timeout_ms must be positive")
self._ain_inference_timeout_ms = value

def get_ain_inference_timeout_grace_ms(self) -> int:
return self._ain_inference_timeout_grace_ms

def set_ain_inference_timeout_grace_ms(self, value: int) -> None:
if value <= 0:
raise ValueError("ain_inference_timeout_grace_ms must be positive")
self._ain_inference_timeout_grace_ms = value

def get_ain_inference_batch_max_requests(self) -> int:
return self._ain_inference_batch_max_requests

def set_ain_inference_batch_max_requests(self, value: int) -> None:
if value < 1:
raise ValueError("ain_inference_batch_max_requests must be positive")
self._ain_inference_batch_max_requests = value

def get_ain_inference_batch_input_points(self) -> int:
return self._ain_inference_batch_input_points

def set_ain_inference_batch_input_points(self, value: int) -> None:
if value < 1:
raise ValueError("ain_inference_batch_input_points must be positive")
self._ain_inference_batch_input_points = value

def get_ain_rpc_max_concurrent_client_num(self) -> int:
return self._ain_rpc_max_concurrent_client_num

def set_ain_rpc_max_concurrent_client_num(self, value: int) -> None:
if value < 1:
raise ValueError("ain_rpc_max_concurrent_client_num must be positive")
self._ain_rpc_max_concurrent_client_num = value

def get_ain_rpc_port(self) -> int:
return self._ain_rpc_port

def get_ain_rpc_max_frame_size(self) -> int:
return self._ain_rpc_max_frame_size

def set_ain_rpc_max_frame_size(self, value: int) -> None:
if not 0 < value <= 0x3FFFFFFF:
raise ValueError("ain_rpc_max_frame_size must be between 1 and 1073741823")
self._ain_rpc_max_frame_size = value

def get_ain_config_node_max_frame_size(self) -> int:
return self._ain_config_node_max_frame_size

def set_ain_config_node_max_frame_size(self, value: int) -> None:
if not 0 < value <= 0x3FFFFFFF:
raise ValueError(
"ain_config_node_max_frame_size must be between 1 and 1073741823"
)
self._ain_config_node_max_frame_size = value

def set_ain_rpc_port(self, ain_rpc_port: int) -> None:
self._ain_rpc_port = ain_rpc_port

Expand All @@ -162,6 +236,8 @@ def get_ain_inference_max_output_length(self) -> int:
def set_ain_inference_max_output_length(
self, ain_inference_max_output_length: int
) -> None:
if ain_inference_max_output_length <= 0:
raise ValueError("ain_inference_max_output_length must be positive")
self._ain_inference_max_output_length = ain_inference_max_output_length

def get_ain_inference_model_mem_usage_map(self) -> dict[str, int]:
Expand Down Expand Up @@ -327,10 +403,49 @@ def _load_config_from_file(self) -> None:
)
return

# noinspection PyBroadException
try:
file_configs = load_properties(conf_file)
except Exception as error:
logger.warning("Cannot read AINode conf file: {}".format(error))
return

for key, setter in (
("ain_rpc_max_frame_size", self._config.set_ain_rpc_max_frame_size),
(
"ain_config_node_max_frame_size",
self._config.set_ain_config_node_max_frame_size,
),
(
"ain_inference_max_output_length",
self._config.set_ain_inference_max_output_length,
),
(
"ain_inference_max_inflight",
self._config.set_ain_inference_max_inflight,
),
("ain_inference_timeout_ms", self._config.set_ain_inference_timeout_ms),
(
"ain_inference_timeout_grace_ms",
self._config.set_ain_inference_timeout_grace_ms,
),
(
"ain_inference_batch_max_requests",
self._config.set_ain_inference_batch_max_requests,
),
(
"ain_inference_batch_input_points",
self._config.set_ain_inference_batch_input_points,
),
(
"ain_rpc_max_concurrent_client_num",
self._config.set_ain_rpc_max_concurrent_client_num,
),
):
if key in file_configs:
setter(int(file_configs[key]))

# noinspection PyBroadException
try:
config_keys = file_configs.keys()

if "ain_rpc_address" in config_keys:
Expand Down
1 change: 1 addition & 0 deletions iotdb-core/ainode/iotdb/ainode/core/constant.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
AINODE_INFERENCE_MODEL_MEM_USAGE_MAP = {
"sundial": 1036 * 1024**2, # 1036 MiB
"timer_xl": 856 * 1024**2, # 856 MiB
"chronos2": 846 * 1024**2, # 846 MiB
} # the memory usage of each model in bytes

AINODE_INFERENCE_MEMORY_USAGE_RATIO = 0.2 # the device space allocated for inference
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#

import queue
from collections import deque


class BoundedRequestBatcher:
"""Wait for work, then drain FIFO within request and input-point budgets.

The first request is always admitted. A request larger than the budget is
evaluated alone instead of starving indefinitely. Overflow stays first for
the next batch; empty queues do not impose a fixed polling delay.
"""

def __init__(
self, waiting_queue, stop_event, max_requests=32, max_input_points=65536
):
if max_requests < 1 or max_input_points < 1:
raise ValueError("Batch limits must be positive")
self.waiting_queue = waiting_queue
self.stop_event = stop_event
self.max_requests = max_requests
self.max_input_points = max_input_points
self.pending = None
self.continuations = deque()
self._prefer_continuation = False

def requeue(self, request):
self.continuations.append(request)

def _take(self, block=False):
if self.continuations and self._prefer_continuation:
self._prefer_continuation = False
return self.continuations.popleft()
try:
request = (
self.waiting_queue.get(timeout=0.1)
if block and not self.continuations
else self.waiting_queue.get_nowait()
)
except queue.Empty:
if self.continuations:
return self.continuations.popleft()
raise
self._prefer_continuation = True
return request

@staticmethod
def _points(model_inputs):
return sum(model_input["targets"].numel() for model_input in model_inputs)

def schedule_step(self):
if self.stop_event.is_set():
return []
if self.pending is not None:
first, self.pending = self.pending, None
else:
try:
first = self._take(block=True)
except queue.Empty:
return []
batch = [first]
points = self._points(first.model_inputs)
while len(batch) < self.max_requests and points < self.max_input_points:
try:
candidate = self._take()
except queue.Empty:
break
cost = self._points(candidate.model_inputs)
if points + cost > self.max_input_points:
self.pending = candidate
break
points += cost
batch.append(candidate)
return batch
Loading