diff --git a/iotdb-client/client-py/iotdb/utils/iotdb_rpc_dataset.py b/iotdb-client/client-py/iotdb/utils/iotdb_rpc_dataset.py index bcb259c6f4263..47a6b5d40561e 100644 --- a/iotdb-client/client-py/iotdb/utils/iotdb_rpc_dataset.py +++ b/iotdb-client/client-py/iotdb/utils/iotdb_rpc_dataset.py @@ -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__( @@ -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: diff --git a/iotdb-core/ainode/README.md b/iotdb-core/ainode/README.md index 1dd055006e504..318bf5b61d0f9 100644 --- a/iotdb-core/ainode/README.md +++ b/iotdb-core/ainode/README.md @@ -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. diff --git a/iotdb-core/ainode/iotdb/ainode/core/config.py b/iotdb-core/ainode/iotdb/ainode/core/config.py index 53217f6c27b5b..d33ceb528ade6 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/config.py +++ b/iotdb-core/ainode/iotdb/ainode/core/config.py @@ -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 @@ -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 @@ -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]: @@ -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: diff --git a/iotdb-core/ainode/iotdb/ainode/core/constant.py b/iotdb-core/ainode/iotdb/ainode/core/constant.py index 1eb79085bcfa0..11abf5c07b5e2 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/constant.py +++ b/iotdb-core/ainode/iotdb/ainode/core/constant.py @@ -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 diff --git a/iotdb-core/ainode/iotdb/ainode/core/inference/batcher/bounded_request_batcher.py b/iotdb-core/ainode/iotdb/ainode/core/inference/batcher/bounded_request_batcher.py new file mode 100644 index 0000000000000..b0be0b98cc305 --- /dev/null +++ b/iotdb-core/ainode/iotdb/ainode/core/inference/batcher/bounded_request_batcher.py @@ -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 diff --git a/iotdb-core/ainode/iotdb/ainode/core/inference/inference_request.py b/iotdb-core/ainode/iotdb/ainode/core/inference/inference_request.py index 43380aa1a08d1..482a0244af107 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/inference/inference_request.py +++ b/iotdb-core/ainode/iotdb/ainode/core/inference/inference_request.py @@ -16,9 +16,13 @@ # under the License. # +import os import threading +import time +from dataclasses import dataclass from typing import Any +import numpy as np import torch from iotdb.ainode.core.log import Logger @@ -31,25 +35,147 @@ class InferenceRequestState: WAITING = "waiting" RUNNING = "running" FINISHED = "finished" + FAILED = "failed" + + +def _normalize_targets_for_batch(targets: torch.Tensor) -> torch.Tensor: + if targets.ndim == 1: + return targets.unsqueeze(0) + return targets + + +@dataclass +class _CpuTensorPayload: + values: np.ndarray + + +def _cpu_tensor_bytes(value): + if isinstance(value, torch.Tensor): + return value.numel() * value.element_size() + if isinstance(value, dict): + return sum(_cpu_tensor_bytes(x) for x in value.values()) + if isinstance(value, (list, tuple)): + return sum(_cpu_tensor_bytes(x) for x in value) + return 0 + + +def _map_cpu_tensors(value, restore=False): + if restore and isinstance(value, _CpuTensorPayload): + return torch.from_numpy(value.values) + if not restore and isinstance(value, torch.Tensor) and value.device.type == "cpu": + try: + return _CpuTensorPayload(value.detach().numpy().copy()) + except (TypeError, RuntimeError): + # Preserve Torch transport for unsupported NumPy dtypes/layouts. + return value + if isinstance(value, dict): + return {key: _map_cpu_tensors(item, restore) for key, item in value.items()} + if isinstance(value, list): + return [_map_cpu_tensors(item, restore) for item in value] + if isinstance(value, tuple): + return tuple(_map_cpu_tensors(item, restore) for item in value) + return value + + +def _contains_tensor(value): + if isinstance(value, torch.Tensor): + return True + if isinstance(value, dict): + return any(_contains_tensor(item) for item in value.values()) + if isinstance(value, (list, tuple)): + return any(_contains_tensor(item) for item in value) + return False + + +@dataclass +class InferenceRequestTransfer: + """CPU array snapshot that can cross a routing process without tensor rebuilds.""" + + state: dict + + @classmethod + def from_request(cls, request): + if os.environ.get("AINODE_REQUEST_IPC", "torch") != "numpy": + return request + state = request.__getstate__() + fields = ("model_inputs", "inputs", "output_tensor") + if not state.get("_cpu_array_ipc") or any( + _contains_tensor(state[name]) for name in fields + ): + # Keep the existing Torch/storage transport for large payloads and + # unsupported NumPy dtypes/layouts, including mixed payloads. + return request + return cls(state) + + def into_request(self): + request = InferenceRequest.__new__(InferenceRequest) + request.__dict__.update(self.state) + return request class InferenceRequest: + def __getstate__(self): + state = self.__dict__.copy() + fields = ("model_inputs", "inputs", "output_tensor") + # Small inference payloads cost less to copy than to exchange multiple + # Torch storage handles. Large payloads retain shared-memory transport. + if ( + os.environ.get("AINODE_REQUEST_IPC", "torch") == "numpy" + and sum(_cpu_tensor_bytes(state[name]) for name in fields) <= 262144 + ): + for name in fields: + state[name] = _map_cpu_tensors(state[name]) + state["_cpu_array_ipc"] = True + return state + + def __setstate__(self, state): + if state.pop("_cpu_array_ipc", False): + for name in ("model_inputs", "inputs", "output_tensor"): + state[name] = _map_cpu_tensors(state[name], restore=True) + self.__dict__.update(state) + + def restore_cpu_payload(self): + """Restore deferred CPU arrays only where the input tensors are consumed.""" + if self.__dict__.get("_cpu_array_ipc", False): + self.__setstate__(self.__dict__.copy()) + self.__dict__.pop("_cpu_array_ipc", None) + def __init__( self, req_id: str, model_id: str, - inputs: torch.Tensor, + inputs: torch.Tensor | None = None, output_length: int = 96, + model_inputs: list[dict[str, Any]] | None = None, + inference_attrs: dict[str, Any] | None = None, **infer_kwargs, ): + self.deadline = infer_kwargs.pop("_deadline", None) + self.model_inputs = self._init_model_inputs(inputs, model_inputs) + + if inputs is None: + inputs = torch.stack( + [ + _normalize_targets_for_batch(data["targets"]) + for data in self.model_inputs + ], + dim=0, + ) + while inputs.ndim < 3: inputs = inputs.unsqueeze(0) self.req_id = req_id self.model_id = model_id self.inputs = inputs - self.infer_kwargs = infer_kwargs - self.output_length = output_length + self.inference_attrs = dict(inference_attrs or {}) + self.inference_attrs.update(infer_kwargs) + if "output_length" not in self.inference_attrs: + self.inference_attrs["output_length"] = output_length + self.infer_kwargs = self.inference_attrs + self.output_length = int( + self.inference_attrs.get("output_length", output_length) + ) self.batch_size = inputs.size(0) self.target_count = inputs.size(1) @@ -58,21 +184,45 @@ def __init__( self.cur_step_idx = 0 # Current write position in the output step index self.assigned_pool_id = -1 # The pool handling this request self.assigned_device_id = -1 # The device handling this request + self.error: str | None = None # Preallocate output buffer [batch_size, target_count, output_length] self.output_tensor = torch.zeros( - self.batch_size, self.target_count, output_length, device="cpu" + self.batch_size, self.target_count, self.output_length, device="cpu" ) + @staticmethod + def _init_model_inputs( + inputs: torch.Tensor | None, model_inputs: list[dict[str, Any]] | None + ) -> list[dict[str, Any]]: + if model_inputs is not None: + if not model_inputs: + raise ValueError("model_inputs must not be empty.") + return model_inputs + if inputs is None: + raise ValueError("Either inputs or model_inputs must be provided.") + + while inputs.ndim < 3: + inputs = inputs.unsqueeze(0) + return [{"targets": inputs[i]} for i in range(inputs.size(0))] + + def expired(self): + return self.deadline is not None and time.monotonic() >= self.deadline + def mark_running(self): self.state = InferenceRequestState.RUNNING def mark_finished(self): self.state = InferenceRequestState.FINISHED + def mark_failed(self, error: str): + self.error = error + self.state = InferenceRequestState.FAILED + def is_finished(self) -> bool: return ( self.state == InferenceRequestState.FINISHED + or self.state == InferenceRequestState.FAILED or self.cur_step_idx >= self.output_length ) @@ -99,6 +249,40 @@ def get_final_output(self) -> torch.Tensor: return self.output_tensor[:, :, : self.cur_step_idx] +@dataclass +class InferenceResult: + """Return only completion data; numpy uses in-band IPC, not Torch FD handles.""" + + req_id: str + output: np.ndarray | None = None + error: str | None = None + + @classmethod + def from_request(cls, request): + output = ( + None + if request.error is not None + else request.get_final_output().detach().cpu().numpy().copy() + ) + return cls(request.req_id, output, request.error) + + def get_final_output(self): + if self.output is None: + raise ValueError("Failed inference has no output") + return torch.from_numpy(self.output) + + def get_rpc_output(self): + """Keep the native CPU array for RPC encoding; preserve the Tensor API.""" + if ( + isinstance(self.output, np.ndarray) + and self.output.dtype.isnative + and self.output.dtype.kind in "biuf" + and self.output.dtype.itemsize <= 8 + ): + return self.output + return self.get_final_output() + + class InferenceRequestProxy: """ Wrap the raw request for handling multiprocess processing. @@ -107,22 +291,43 @@ class InferenceRequestProxy: def __init__(self, req_id: str): self.req_id = req_id self.result = None + self.exception = None + self._done = False self._counter: AtomicInt = None self._lock = threading.Lock() self._condition = threading.Condition(self._lock) - def set_result(self, result: Any): - with self._lock: + def _complete(self, result=None, exception=None): + with self._condition: + if self._done: + return False self.result = result + self.exception = exception + self._done = True if self._counter is not None: self._counter.decrement_and_get() self._condition.notify_all() + return True + + def set_result(self, result: Any): + return self._complete(result=result) + + def set_exception(self, exception: Exception): + return self._complete(exception=exception) def set_counter(self, counter: AtomicInt): with self._lock: self._counter = counter - def wait_for_result(self) -> Any: - with self._lock: - self._condition.wait() + def wait_for_result(self, deadline=None) -> Any: + with self._condition: + while not self._done: + remaining = None if deadline is None else deadline - time.monotonic() + if remaining is not None and remaining <= 0: + # The work still owns its admission slot and pool counter. + # Only a result or confirmed worker termination releases them. + raise TimeoutError("AINode inference deadline exceeded") + self._condition.wait(remaining) + if self.exception is not None: + raise self.exception return self.result diff --git a/iotdb-core/ainode/iotdb/ainode/core/inference/inference_request_pool.py b/iotdb-core/ainode/iotdb/ainode/core/inference/inference_request_pool.py index 8121d4fecd8c6..37f9ef783bffa 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/inference/inference_request_pool.py +++ b/iotdb-core/ainode/iotdb/ainode/core/inference/inference_request_pool.py @@ -17,10 +17,11 @@ # import random -import threading import time +import traceback from collections import defaultdict from enum import Enum +from typing import Any import numpy as np import torch @@ -29,16 +30,19 @@ from iotdb.ainode.core.config import AINodeDescriptor from iotdb.ainode.core.constant import INFERENCE_LOG_FILE_NAME_PREFIX_TEMPLATE from iotdb.ainode.core.inference.batcher.basic_batcher import BasicBatcher -from iotdb.ainode.core.inference.inference_request import InferenceRequest +from iotdb.ainode.core.inference.batcher.bounded_request_batcher import ( + BoundedRequestBatcher, +) +from iotdb.ainode.core.inference.inference_request import ( + InferenceRequest, + InferenceResult, +) from iotdb.ainode.core.inference.pipeline.basic_pipeline import ( ChatPipeline, ClassificationPipeline, ForecastPipeline, ) from iotdb.ainode.core.inference.pipeline.pipeline_loader import load_pipeline -from iotdb.ainode.core.inference.request_scheduler.basic_request_scheduler import ( - BasicRequestScheduler, -) from iotdb.ainode.core.log import Logger from iotdb.ainode.core.manager.device_manager import DeviceManager from iotdb.ainode.core.model.model_storage import ModelInfo @@ -47,18 +51,28 @@ class PoolState(Enum): INITIALIZING = "INITIALIZING" RUNNING = "RUNNING" + DRAINING = "DRAINING" STOPPING = "STOPPING" + FAILED = "FAILED" + + +class _WorkerStopFlag: + def __init__(self): + self._value = mp.get_context("spawn").RawValue("b", False) + def is_set(self): + return bool(self._value.value) -class InferenceRequestPool(mp.Process): + def set(self): + self._value.value = True + + +class InferenceRequestPool(mp.get_context("spawn").Process): """ The request pool to handle inference for a specific model. """ FIX_SEED = 2021 - WAITING_INTERVAL_IN_MS = ( - AINodeDescriptor().get_config().get_ain_inference_batch_interval_in_ms() - ) # How often to check for requests in the waiting/running queue def __init__( self, @@ -67,25 +81,23 @@ def __init__( device: torch.device, request_queue: mp.Queue, result_queue: mp.Queue, - ready_event, - **pool_kwargs, ): super().__init__() self.pool_id = pool_id self.model_info = model_info - self.pool_kwargs = pool_kwargs - self.ready_event = ready_event self.device = device - self._threads = [] self._waiting_queue = request_queue # Requests that are waiting to be processed - self._running_queue = mp.Queue() # Requests that are currently being processed self._finished_queue = result_queue # Requests that are finished - self._request_scheduler = BasicRequestScheduler( - self._waiting_queue, self._running_queue, self._finished_queue, self.pool_id - ) self._batcher = BasicBatcher() - self._stop_event = mp.Event() + self._stop_event = _WorkerStopFlag() + config = AINodeDescriptor().get_config() + self._request_scheduler = BoundedRequestBatcher( + self._waiting_queue, + self._stop_event, + config.get_ain_inference_batch_max_requests(), + config.get_ain_inference_batch_input_points(), + ) self._backend = None self._inference_pipeline = None @@ -96,119 +108,167 @@ def __init__( torch.manual_seed(self.FIX_SEED) np.random.seed(self.FIX_SEED) - def _activate_requests(self): - requests = self._request_scheduler.schedule_activate() - for request in requests: - request.mark_running() - self._running_queue.put(request) - self._logger.debug( - f"[Inference][{self.device}][Pool-{self.pool_id}][Req-{request.req_id}] Request is activated with inputs shape {request.inputs.shape}" + @staticmethod + def _freeze_inference_attrs(value: Any): + if isinstance(value, dict): + return tuple( + sorted( + (key, InferenceRequestPool._freeze_inference_attrs(item)) + for key, item in value.items() + ) ) + if isinstance(value, (list, tuple)): + return tuple( + InferenceRequestPool._freeze_inference_attrs(item) for item in value + ) + try: + hash(value) + except TypeError: + return repr(value) + return value - def _requests_activate_loop(self): - while not self._stop_event.is_set(): - time.sleep(self.WAITING_INTERVAL_IN_MS / 1000) - self._activate_requests() + def _build_batch_input_list(self, requests: list[InferenceRequest]): + input_device = getattr(self._inference_pipeline, "input_device", self.device) + batch_inputs = self._backend.move_tensor( + self._batcher.batch_request(requests), input_device + ) + return [{"targets": batch_inputs[i]} for i in range(batch_inputs.size(0))] def _step(self): all_requests: list[InferenceRequest] = self._request_scheduler.schedule_step() grouped_requests = defaultdict(list) for req in all_requests: - key = (req.target_count, req.input_length, req.output_length) + if req.expired(): + req.mark_failed("AINode inference deadline exceeded before execution") + self._finished_queue.put(InferenceResult.from_request(req)) + continue + req.mark_running() + if isinstance(self._inference_pipeline, ForecastPipeline): + try: + ForecastPipeline._base_preprocess( + self._inference_pipeline, + req.model_inputs, + **req.inference_attrs, + ) + except Exception as error: + req.mark_failed(str(error)) + self._finished_queue.put(InferenceResult.from_request(req)) + continue + if req.inference_attrs.get("predict_batches_jointly", False): + key = (req.req_id,) + else: + key = ( + req.target_count, + req.input_length, + req.output_length, + self._freeze_inference_attrs(req.inference_attrs), + ) grouped_requests[key].append(req) grouped_requests = list(grouped_requests.values()) for requests in grouped_requests: - batch_inputs = self._backend.move_tensor( - self._batcher.batch_request(requests), self.device - ) - batch_input_list = [] - for i in range(batch_inputs.size(0)): - batch_input_list.append({"targets": batch_inputs[i]}) - batch_inputs = self._inference_pipeline.preprocess( - batch_input_list, - output_length=requests[0].output_length, - auto_adapt=True, - ) - if isinstance(self._inference_pipeline, ForecastPipeline): - batch_output = self._inference_pipeline.forecast( - batch_inputs, - output_length=requests[0].output_length, - revin=True, + live_requests = [] + for request in requests: + if request.expired(): + request.mark_failed( + "AINode inference deadline exceeded before execution" + ) + self._finished_queue.put(InferenceResult.from_request(request)) + else: + live_requests.append(request) + requests = live_requests + if not requests: + continue + try: + inference_attrs = requests[0].inference_attrs + batch_input_list = self._build_batch_input_list(requests) + batch_inputs = self._inference_pipeline.preprocess( + batch_input_list, + **inference_attrs, ) - elif isinstance(self._inference_pipeline, ClassificationPipeline): - batch_output = self._inference_pipeline.classify( - batch_inputs, - # more infer kwargs can be added here + if isinstance(self._inference_pipeline, ForecastPipeline): + batch_output = self._inference_pipeline.forecast( + batch_inputs, + **inference_attrs, + ) + elif isinstance(self._inference_pipeline, ClassificationPipeline): + batch_output = self._inference_pipeline.classify( + batch_inputs, + **inference_attrs, + ) + elif isinstance(self._inference_pipeline, ChatPipeline): + batch_output = self._inference_pipeline.chat( + batch_inputs, + **inference_attrs, + ) + else: + batch_output = None + self._logger.error("[Inference] Unsupported pipeline type.") + batch_output_list = self._inference_pipeline.postprocess( + batch_output, **inference_attrs ) - elif isinstance(self._inference_pipeline, ChatPipeline): - batch_output = self._inference_pipeline.chat( - batch_inputs, - # more infer kwargs can be added here + # Results cross the process boundary on the CPU. Transfer the + # whole batch once; per-request GPU buffers add needless copies. + batch_output = ( + torch.stack([output for output in batch_output_list], dim=0) + .detach() + .cpu() ) - else: - batch_output = None - self._logger.error("[Inference] Unsupported pipeline type.") - batch_output_list = self._inference_pipeline.postprocess(batch_output) - batch_output = torch.stack([output for output in batch_output_list], dim=0) + offset = 0 + for request in requests: + cur_batch_size = request.batch_size + cur_output = batch_output[offset : offset + cur_batch_size] + offset += cur_batch_size + request.write_step_output(cur_output) - offset = 0 - for request in requests: - request.output_tensor = self._backend.move_tensor( - request.output_tensor, self.device + if request.is_finished(): + self._finished_queue.put(InferenceResult.from_request(request)) + self._logger.debug( + f"[Inference][{self.device}][Pool-{self.pool_id}][ID-{request.req_id}] Request is finished" + ) + else: + self._request_scheduler.requeue(request) + self._logger.debug( + f"[Inference][{self.device}][Pool-{self.pool_id}][ID-{request.req_id}] Request is not finished, re-queueing" + ) + except Exception as e: + error_traceback = traceback.format_exc() + self._logger.error( + f"[Inference][{self.device}][Pool-{self.pool_id}] Failed to execute requests " + f"{[request.req_id for request in requests]}: {e}\n{error_traceback}" ) - cur_batch_size = request.batch_size - cur_output = batch_output[offset : offset + cur_batch_size] - offset += cur_batch_size - request.write_step_output(cur_output) - - if request.is_finished(): - # ensure the output tensor is on CPU before sending to result queue - request.output_tensor = request.output_tensor.cpu() - self._finished_queue.put(request) - self._logger.debug( - f"[Inference][{self.device}][Pool-{self.pool_id}][ID-{request.req_id}] Request is finished" - ) - else: - self._waiting_queue.put(request) - self._logger.debug( - f"[Inference][{self.device}][Pool-{self.pool_id}][ID-{request.req_id}] Request is not finished, re-queueing" - ) + for request in requests: + request.mark_failed(f"{e}\n{error_traceback}") + self._finished_queue.put(InferenceResult.from_request(request)) + continue + return def _requests_execute_loop(self): while not self._stop_event.is_set(): - time.sleep(self.WAITING_INTERVAL_IN_MS / 1000) self._step() def run(self): + self._waiting_queue._writer.close() + self._finished_queue._reader.close() self._logger = Logger( INFERENCE_LOG_FILE_NAME_PREFIX_TEMPLATE.format(self.device) ) self._backend = DeviceManager() - self._request_scheduler.device = self.device - self._inference_pipeline = load_pipeline(self.model_info, self.device) - self.ready_event.set() + try: + self._inference_pipeline = load_pipeline(self.model_info, self.device) + except Exception as error: + self._finished_queue.put((self.pool_id, str(error))) + while not self._stop_event.is_set(): + time.sleep(0.05) + return + self._finished_queue.put((self.pool_id, None)) - activate_daemon = threading.Thread( - target=self._requests_activate_loop, daemon=True - ) - self._threads.append(activate_daemon) - activate_daemon.start() - execute_daemon = threading.Thread( - target=self._requests_execute_loop, daemon=True - ) - self._threads.append(execute_daemon) - execute_daemon.start() - self._logger.info( - f"[Inference][{self.device}][Pool-{self.pool_id}] InferenceRequestPool for model {self.model_info.model_id} is activated." - ) - for thread in self._threads: - thread.join() self._logger.info( - f"[Inference][{self.device}][Pool-{self.pool_id}] InferenceRequestPool for model {self.model_info.model_id} exited cleanly." + f"[Inference][{self.device}][Pool-{self.pool_id}] Worker ready" ) + self._requests_execute_loop() def stop(self): self._stop_event.set() diff --git a/iotdb-core/ainode/iotdb/ainode/core/inference/pipeline/basic_pipeline.py b/iotdb-core/ainode/iotdb/ainode/core/inference/pipeline/basic_pipeline.py index f4bf914a84668..08fa1b83e056d 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/inference/pipeline/basic_pipeline.py +++ b/iotdb-core/ainode/iotdb/ainode/core/inference/pipeline/basic_pipeline.py @@ -113,6 +113,17 @@ def _base_preprocess( raise ValueError( f"'targets' must be torch.Tensor, but got {type(targets)} at index {idx}." ) + if not targets.numel(): + raise ValueError("Targets must not be empty") + if torch.isinf(targets).any(): + raise ValueError("Targets must not contain infinite values") + if ( + not getattr(self, "supports_missing_values", False) + and torch.isnan(targets).any() + ): + raise ValueError( + "This model requires missing observations to be repaired before FORECAST" + ) if targets.ndim not in [1, 2]: raise ValueError( f"'targets' must have 1 or 2 dimensions, but got {targets.ndim} dimensions at index {idx}." diff --git a/iotdb-core/ainode/iotdb/ainode/core/inference/pool_controller.py b/iotdb-core/ainode/iotdb/ainode/core/inference/pool_controller.py index 73bf01c3f7a63..0e306a0a4f9f0 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/inference/pool_controller.py +++ b/iotdb-core/ainode/iotdb/ainode/core/inference/pool_controller.py @@ -15,12 +15,12 @@ # specific language governing permissions and limitations # under the License. # -import concurrent +import os import queue import random import threading -from concurrent.futures import wait -from queue import Empty +import time +from concurrent.futures import ThreadPoolExecutor, wait from typing import Dict, Optional import torch @@ -36,18 +36,47 @@ PoolState, ) from iotdb.ainode.core.inference.pool_group import PoolGroup -from iotdb.ainode.core.inference.pool_scheduler.basic_pool_scheduler import ( - BasicPoolScheduler, - ScaleActionType, -) from iotdb.ainode.core.log import Logger from iotdb.ainode.core.manager.model_manager import ModelManager from iotdb.ainode.core.util.atmoic_int import AtomicInt -from iotdb.ainode.core.util.batch_executor import BatchExecutor from iotdb.ainode.core.util.decorator import synchronized from iotdb.ainode.core.util.thread_name import ThreadName logger = Logger() +_SPAWN = mp.get_context("spawn") + + +def _close_request_queue(request_queue, deadline): + """Wake a full parent feeder after its only reader has exited.""" + request_queue.cancel_join_thread() + request_queue._reader.close() + request_queue.close() + feeder = request_queue._thread + if feeder is not None: + feeder.join(max(0, deadline - time.monotonic())) + if feeder.is_alive(): + raise RuntimeError("Inference request feeder did not exit") + request_queue._writer.close() + + +def configure_request_pipe(request_queue): + """Optionally hold a small-request batch in the pipe, before the worker starts.""" + requested = int(os.environ.get("AINODE_REQUEST_PIPE_BYTES", "0")) + if not requested: + return None + if not 4096 <= requested <= 1048576: + raise ValueError("Request pipe size must be 4096..1048576 bytes") + try: + import fcntl + + return fcntl.fcntl( + request_queue._writer.fileno(), fcntl.F_SETPIPE_SZ, requested + ) + except (ImportError, AttributeError, OSError) as error: + logger.warning( + f"Request pipe sizing unavailable; keeping platform default: {error}" + ) + return None class PoolController: @@ -59,20 +88,26 @@ def __init__(self, result_queue: mp.Queue): self._model_manager = ModelManager() # structure: {model_id: {device_id: PoolGroup}} self._request_pool_map: Dict[str, Dict[torch.device, PoolGroup]] = {} + self._registry_lock = threading.RLock() + self._managed_models = set() + self._desired = {} + self._ready = {} + self._fault = None + self._unconfirmed_start = False + self._transition_counts = {} self._new_pool_id = AtomicInt() self._result_queue = result_queue - self._pool_scheduler = BasicPoolScheduler(self._request_pool_map) self._stop_event = threading.Event() # for pool instances control - self._task_queue = queue.Queue() + self._task_queue = queue.Queue(maxsize=64) self._pool_control_worker_thread = threading.Thread( target=self._worker_loop, daemon=True ) - self._pool_control_worker_thread.start() - self._executor = BatchExecutor( - thread_name_prefix=ThreadName.INFERENCE_POOL_CONTROLLER.value + self._executor = ThreadPoolExecutor( + max_workers=8, thread_name_prefix=ThreadName.INFERENCE_POOL_CONTROLLER.value ) + self._pool_control_worker_thread.start() # =============== Automatic Pool Management (Developing) =============== @synchronized(threading.Lock()) @@ -141,9 +176,7 @@ def load_model(self, model_id: str, device_id_list: list[torch.device]): model_id (str): The ID of the model to be loaded. device_id_list (list[torch.device]): List of device_ids where the model should be loaded. """ - self._task_queue.put( - (self._load_one_model_task, (model_id, device_id_list), {}) - ) + self._enqueue_model_task(self._load_one_model_task, model_id, device_id_list) def unload_model(self, model_id: str, device_id_list: list[torch.device]): """ @@ -152,69 +185,171 @@ def unload_model(self, model_id: str, device_id_list: list[torch.device]): model_id (str): The ID of the model to be unloaded. device_id_list (list[torch.device]): List of device_ids where the model should be unloaded. """ - self._task_queue.put( - (self._unload_one_model_task, (model_id, device_id_list), {}) - ) + self._enqueue_model_task(self._unload_one_model_task, model_id, device_id_list) + + def _enqueue_model_task(self, task, model_id, device_ids): + with self._registry_lock: + if self._stop_event.is_set(): + raise InferenceModelInternalException("Model pool is stopping") + device_ids = list(dict.fromkeys(device_ids)) + loading = task == self._load_one_model_task + if loading: + occupied = { + device for owner, device in self._desired if owner != model_id + } + device_ids = [device for device in device_ids if device not in occupied] + else: + device_ids = [ + device + for device in device_ids + if (model_id, device) in self._desired + or self.has_request_pools(model_id, device) + ] + if not device_ids: + return + load_token = object() if loading else None + kwargs = {"load_token": load_token} if loading else {} + try: + self._task_queue.put_nowait((task, (model_id, device_ids), kwargs)) + except queue.Full: + raise InferenceModelInternalException("Model lifecycle queue is full") + self._managed_models.add(model_id) + self._transition_counts[model_id] = ( + self._transition_counts.get(model_id, 0) + 1 + ) + targets = {(model_id, device) for device in device_ids} + if loading: + self._desired.update(dict.fromkeys(targets, load_token)) + else: + for target in targets: + self._desired.pop(target, None) + + def desired_residency(self): + with self._registry_lock: + return set(self._desired), set(self._managed_models) + + def restore_residency(self, desired, managed, deadline): + self._desired.update(dict.fromkeys(desired)) + self._managed_models.update(managed) + for model_id, device in sorted( + desired, key=lambda target: (str(target[1]), target[0]) + ): + self._expand_pools_on_device(model_id, device, 1, deadline) + fault = self.worker_fault() + if fault is not None: + raise RuntimeError(fault) + + def requires_loaded_pool(self, model_id): + with self._registry_lock: + return model_id in self._managed_models + + def pool_snapshot(self): + with self._registry_lock: + groups = [ + group + for devices in self._request_pool_map.values() + for group in devices.values() + ] + result = {} + for group in groups: + with group._lock: + for pool_id, (process, _) in group.pool_group.items(): + result[pool_id] = (process, group.pool_states.get(pool_id), group) + return result + + def worker_fault(self): + with self._registry_lock: + if self._fault is not None: + return self._fault + for pool_id, (process, state, group) in self.pool_snapshot().items(): + if state == PoolState.FAILED or ( + state in (PoolState.RUNNING, PoolState.DRAINING, PoolState.STOPPING) + and not process.is_alive() + and not ( + state == PoolState.STOPPING + and process.exitcode == 0 + and group.get_load(pool_id) == 0 + ) + ): + return f"Inference worker {pool_id} exited unexpectedly" + return None + + def mark_ready(self, pool_id, error): + with self._registry_lock: + if pool_id in self._ready: + self._ready[pool_id].append(error) def show_loaded_models( self, device_id_list: list[torch.device] ) -> Dict[str, Dict[str, int]]: - """ - Show loaded model instances on the specified devices. - Args: - device_id_list (list[torch.device]): List of device_ids where to examine loaded instances. - Return: - Dict[str, Dict[str, int]]: Dict[device_id, Dict[model_id, Count(instances)]]. - """ - result = {} - for device_id in device_id_list: - device_models = {} - for model_id, device_map in self._request_pool_map.items(): - if device_id in device_map: - pool_group = device_map[device_id] - device_models[model_id] = pool_group.get_running_pool_count() - device_key = ( - device_id.type if device_id.index is None else str(device_id.index) - ) - result[device_key] = device_models - return result + with self._registry_lock: + """ + Show loaded model instances on the specified devices. + Args: + device_id_list (list[torch.device]): List of device_ids where to examine loaded instances. + Return: + Dict[str, Dict[str, int]]: Dict[device_id, Dict[model_id, Count(instances)]]. + """ + result = {} + for device_id in device_id_list: + device_models = {} + for model_id, device_map in self._request_pool_map.items(): + if device_id in device_map: + pool_group = device_map[device_id] + device_models[model_id] = pool_group.get_running_pool_count() + device_key = ( + device_id.type if device_id.index is None else str(device_id.index) + ) + result[device_key] = device_models + return result def _worker_loop(self): while not self._stop_event.is_set(): try: - task = self._task_queue.get(timeout=1) - except Empty: - # Ignore Empty exception and continue the loop + task = self._task_queue.get(timeout=0.1) + except queue.Empty: continue - if task is None: - self._task_queue.task_done() - logger.info( - "PoolController received task None, the worker loop is existed." - ) - break task_fn, args, kwargs = task try: - task_fn(*args, **kwargs) + if not self._stop_event.is_set(): + task_fn(*args, **kwargs) except Exception as e: logger.error(f"Error executing task: {e}") finally: + with self._registry_lock: + model_id = args[0] + self._transition_counts[model_id] -= 1 self._task_queue.task_done() - def _load_one_model_task(self, model_id: str, device_id_list: list[torch.device]): + def _load_one_model_task( + self, model_id: str, device_id_list: list[torch.device], load_token: object + ): def _load_one_model_on_device_task(device_id: torch.device): if not self.has_pool_on_device(device_id): - self._expand_pools_on_device(model_id, device_id, 1) + try: + self._expand_pools_on_device(model_id, device_id, 1) + except Exception: + with self._registry_lock: + target = (model_id, device_id) + if ( + self._desired.get(target) is load_token + and not self._stop_event.is_set() + and not self.has_pool_on_device(device_id) + ): + del self._desired[target] + raise else: logger.info( f"[Inference][{device_id}] There are already pools on this device." ) - load_model_futures = self._executor.submit_batch( - device_id_list, _load_one_model_on_device_task - ) - concurrent.futures.wait( - load_model_futures, return_when=concurrent.futures.ALL_COMPLETED - ) + load_model_futures = [ + self._executor.submit(_load_one_model_on_device_task, device) + for device in device_id_list + ] + wait(load_model_futures) + for future in load_model_futures: + future.result() def _unload_one_model_task(self, model_id: str, device_id_list: list[torch.device]): def _unload_one_model_on_device_task(device_id: torch.device): @@ -225,12 +360,13 @@ def _unload_one_model_on_device_task(device_id: torch.device): f"[Inference][{device_id}] Model {model_id} is not installed." ) - unload_model_futures = self._executor.submit_batch( - device_id_list, _unload_one_model_on_device_task - ) - concurrent.futures.wait( - unload_model_futures, return_when=concurrent.futures.ALL_COMPLETED - ) + unload_model_futures = [ + self._executor.submit(_unload_one_model_on_device_task, device) + for device in device_id_list + ] + wait(unload_model_futures) + for future in unload_model_futures: + future.result() # def _load_model_task(self, model_id: str, device_id_list: list[torch.device]): # def _load_model_on_device_task(device_id: torch.device): @@ -287,7 +423,7 @@ def _unload_one_model_on_device_task(device_id: torch.device): # ) def _expand_pools_on_device( - self, model_id: str, device_id: torch.device, count: int + self, model_id: str, device_id: torch.device, count: int, deadline=None ): """ Expand the pools for the given model_id and device_id sequentially. @@ -298,37 +434,86 @@ def _expand_pools_on_device( """ def _expand_pool_on_device(*_): - request_queue = mp.Queue() + from iotdb.ainode.core.manager.utils import ( + INFERENCE_EXTRA_MEMORY_RATIO, + MODEL_MEM_USAGE_MAP, + evaluate_system_resources, + ) + + ready_deadline = time.monotonic() + 300 if deadline is None else deadline + if self._stop_event.is_set() or time.monotonic() >= ready_deadline: + raise RuntimeError("Model worker startup cancelled") + memory_estimate = MODEL_MEM_USAGE_MAP.get(model_id) + if memory_estimate is not None: + required = memory_estimate * INFERENCE_EXTRA_MEMORY_RATIO + if evaluate_system_resources(device_id)["free_mem"] < required: + raise RuntimeError( + f"Insufficient free memory to load {model_id} on {device_id}" + ) pool_id = self._new_pool_id.get_and_increment() model_info = self._model_manager.get_model_info(model_id) - pool = InferenceRequestPool( - pool_id=pool_id, - model_info=model_info, - device=device_id, - request_queue=request_queue, - result_queue=self._result_queue, - ready_event=mp.Event(), - ) - pool.start() - self._register_pool(model_id, device_id, pool_id, pool, request_queue) - if not pool.ready_event.wait(timeout=300): - logger.error( - f"[Inference][{device_id}][Pool-{pool_id}] Pool failed to be ready in time" - ) - # TODO: retry or decrease the count? this error should be better handled - self._erase_pool(model_id, device_id, pool_id) - else: - self.set_state(model_id, device_id, pool_id, PoolState.RUNNING) - logger.info( - f"[Inference][{device_id}][Pool-{pool_id}] Pool started running for model {model_id}" + request_queue = _SPAWN.Queue() + try: + request_queue._ignore_epipe = True + actual_pipe_size = configure_request_pipe(request_queue) + if actual_pipe_size is not None: + logger.info( + f"Inference request pipe capacity: {actual_pipe_size} bytes" + ) + pool = InferenceRequestPool( + pool_id=pool_id, + model_info=model_info, + device=device_id, + request_queue=request_queue, + result_queue=self._result_queue, ) + with self._registry_lock: + if self._stop_event.is_set() or self._fault is not None: + raise RuntimeError("Model worker startup cancelled") + self._register_pool( + model_id, device_id, pool_id, pool, request_queue + ) + ready = self._ready[pool_id] = [] + try: + pool.start() + except Exception: + if pool.pid is None: + self._unconfirmed_start = True + self._fault = ( + f"Model worker start failed for {model_id} on {device_id}" + ) + raise + except Exception: + if pool_id not in self._ready: + _close_request_queue(request_queue, ready_deadline) + raise + + while not self._stop_event.is_set(): + with self._registry_lock: + if ready: + load_error = ready[0] + if load_error is not None: + break + if pool.is_alive(): + self.set_state( + model_id, device_id, pool_id, PoolState.RUNNING + ) + return + if not pool.is_alive() or time.monotonic() >= ready_deadline: + self._fault = f"Model worker failed to become ready: {model_id} on {device_id}" + raise RuntimeError(self._fault) + self._stop_event.wait(0.05) + if self._stop_event.is_set(): + raise RuntimeError("Model worker startup cancelled") + self._erase_pool(model_id, device_id, pool_id, load_failed=True) + raise RuntimeError( + f"Failed to load {model_id} on {device_id}: {load_error}" + ) - expand_pool_futures = self._executor.submit_batch( - [None for _ in range(count)], _expand_pool_on_device - ) - concurrent.futures.wait( - expand_pool_futures, return_when=concurrent.futures.ALL_COMPLETED - ) + # Loading sequentially prevents simultaneous model copies from all + # observing the same free memory and overcommitting the device. + for _ in range(count): + _expand_pool_on_device() def _shrink_pools_on_device( self, model_id: str, device_id: torch.device, count: int @@ -338,51 +523,22 @@ def _shrink_pools_on_device( TODO: shrink pools in parallel """ - pool_ids = self.get_pool_ids(model_id, device_id) - current_count = len(pool_ids) - if current_count < count: - logger.warning( - f"[Inference] Cannot shrink {count} pools for model {model_id}, only {current_count} pools available." - ) - - # 1. Find pools with zero load and set them to STOP - zero_load_pools = [ - pid for pid in pool_ids if self.get_load(model_id, device_id, pid) == 0 - ] - stop_count = min(len(zero_load_pools), count) - pools_to_stop = zero_load_pools[:stop_count] - - for pid in pools_to_stop: - self.set_state( - model_id, device_id, pid, PoolState.STOPPING - ) # Set to STOPPING state - - remaining_to_close = count - len(pools_to_stop) - if remaining_to_close <= 0: - # close the STOP pools whose load is 0 - for pid in pools_to_stop: - self.get_request_pool(model_id, device_id, pid).stop() - self._erase_pool(model_id, device_id, pid) - return - - # 2. If not enough, randomly select additional pools to set to STOP - candidates = [pid for pid in pool_ids if pid not in pools_to_stop] - additional_stop = random.sample( - candidates, min(remaining_to_close, len(candidates)) - ) # TODO: implement better selection strategy - for pid in additional_stop: - self.set_state( - model_id, device_id, pid, PoolState.STOPPING - ) # Set to STOPPING state - - # 3. Wait for all STOPPING pools to have zero load, then close them - final_stop_pools = pools_to_stop + additional_stop + with self._registry_lock: + pool_ids = self.get_pool_ids(model_id, device_id) + final_stop_pools = sorted( + pool_ids, + key=lambda pool_id: self.get_load(model_id, device_id, pool_id), + )[:count] + for pool_id in final_stop_pools: + if self.get_state(model_id, device_id, pool_id) == PoolState.RUNNING: + self.set_state(model_id, device_id, pool_id, PoolState.DRAINING) while final_stop_pools and not self._stop_event.is_set(): - for pid in final_stop_pools[:]: # iterate over a copy of the list - if self.get_load(model_id, device_id, pid) == 0: - self.get_request_pool(model_id, device_id, pid).stop() - self._erase_pool(model_id, device_id, pid) - final_stop_pools.remove(pid) + for pool_id in final_stop_pools[:]: + if self.get_load(model_id, device_id, pool_id) == 0: + self._erase_pool(model_id, device_id, pool_id) + final_stop_pools.remove(pool_id) + if final_stop_pools: + self._stop_event.wait(0.01) def _register_pool( self, @@ -404,39 +560,55 @@ def _register_pool( f"[Inference][{device_id}][Pool-{pool_id}] Pool initializing for model {model_id}" ) - def _erase_pool(self, model_id: str, device_id: torch.device, pool_id: int): - """ - Erase the specified inference request pool for the given model_id, device_id and pool_id. - """ - pool_group = self.get_request_pools_group(model_id, device_id) - if pool_group: - pool_group.remove_pool(pool_id) - logger.info( - f"[Inference][{device_id}][Pool-{pool_id}] Erase pool for model {model_id}" - ) - # Clean up empty structures - if pool_group and not pool_group.get_pool_ids(): - self._request_pool_map[model_id].pop(device_id, None) - if model_id in self._request_pool_map and not self._request_pool_map[model_id]: - self._request_pool_map.pop(model_id, None) + def _erase_pool(self, model_id, device_id, pool_id, load_failed=False): + with self._registry_lock: + group = self.get_request_pools_group(model_id, device_id) + process = group.get_request_pool(pool_id) + request_queue = group.get_request_queue(pool_id) + if self._stop_event.is_set(): + raise RuntimeError("Model worker shutdown cancelled") + if not process.is_alive() and not (load_failed and process.exitcode == 0): + self._fault = f"Inference worker {pool_id} exited before shutdown" + raise RuntimeError(self._fault) + process.stop() + group.set_state(pool_id, PoolState.STOPPING) + try: + process.join(timeout=2) + if process.exitcode != 0: + raise RuntimeError(f"Inference worker {pool_id} did not exit cleanly") + _close_request_queue(request_queue, time.monotonic() + 2) + except Exception as error: + with self._registry_lock: + self._fault = str(error) + raise + with self._registry_lock: + group.remove_pool(pool_id) + self._ready.pop(pool_id, None) + process.close() + if not group.get_pool_ids(): + self._request_pool_map[model_id].pop(device_id, None) + if not self._request_pool_map[model_id]: + self._request_pool_map.pop(model_id, None) + + # =============== Request Management =============== - # =============== Request Management =============== def add_request(self, req: InferenceRequest, infer_proxy: InferenceRequestProxy): model_id = req.model_id - if not self.has_request_pools(model_id): - logger.error(f"[Inference] No pools found for model {model_id}.") - infer_proxy.set_result(None) - raise InferenceModelInternalException( - "Dispatch request failed, because no inference pools are init." - ) - # TODO: Implement adaptive scaling based on requests.(e.g. lazy initialization) - # self.first_req_init(model_id) - - device_ids = self.get_device_ids(model_id) - device_id = random.choice( - device_ids - ) # TODO: Implement better device selection strategy - self._request_pool_map[model_id][device_id].dispatch_request(req, infer_proxy) + with self._registry_lock: + if self._transition_counts.get(model_id, 0): + raise InferenceModelInternalException( + "Model is loading or unloading; retry after it is ready" + ) + groups = [ + group + for group in self._request_pool_map.get(model_id, {}).values() + if group.get_running_pool_count() + ] + if not groups: + raise InferenceModelInternalException( + "No healthy inference worker; LOAD MODEL before retrying" + ) + random.choice(groups).dispatch_request(req, infer_proxy) # =============== Getters / Setters =============== def get_state( @@ -461,12 +633,13 @@ def set_state( pool_group.set_state(pool_id, state) def get_device_ids(self, model_id) -> list[torch.device]: - """ - Get the list of device IDs for the given model_id, where the corresponding instances are loaded. - """ - if model_id in self._request_pool_map: - return list(self._request_pool_map[model_id].keys()) - return [] + with self._registry_lock: + """ + Get the list of device IDs for the given model_id, where the corresponding instances are loaded. + """ + if model_id in self._request_pool_map: + return list(self._request_pool_map[model_id].keys()) + return [] def get_pool_ids(self, model_id: str, device_id: torch.device) -> list[int]: """ @@ -478,42 +651,46 @@ def get_pool_ids(self, model_id: str, device_id: torch.device) -> list[int]: return [] def has_request_pools(self, model_id: str, device_id: torch.device = None) -> bool: - """ - Check if there are request pools for the given model_id ((optional) and device_id). - """ - if model_id not in self._request_pool_map: - return False - if device_id is not None: - return device_id in self._request_pool_map[model_id] - return True + with self._registry_lock: + """ + Check if there are request pools for the given model_id ((optional) and device_id). + """ + if model_id not in self._request_pool_map: + return False + if device_id is not None: + return device_id in self._request_pool_map[model_id] + return True def has_running_pools(self, model_id: str) -> bool: - """ - Check if there are running pools for the given model_id. - """ - if model_id not in self._request_pool_map: + with self._registry_lock: + """ + Check if there are running pools for the given model_id. + """ + if model_id not in self._request_pool_map: + return False + for device_id, pool_group in self._request_pool_map[model_id].items(): + if pool_group.get_running_pool_count(): + return True return False - for device_id, pool_group in self._request_pool_map[model_id].items(): - if pool_group.get_running_pool_count(): - return True - return False def has_pool_on_device(self, device_id: torch.device) -> bool: """ Check if there are pools on the given device_id. """ - return any(device_id in pools for pools in self._request_pool_map.values()) + with self._registry_lock: + return any(device_id in pools for pools in self._request_pool_map.values()) def get_request_pools_group( self, model_id: str, device_id: torch.device ) -> Optional[PoolGroup]: - if ( - model_id in self._request_pool_map - and device_id in self._request_pool_map[model_id] - ): - return self._request_pool_map[model_id][device_id] - else: - return None + with self._registry_lock: + if ( + model_id in self._request_pool_map + and device_id in self._request_pool_map[model_id] + ): + return self._request_pool_map[model_id][device_id] + else: + return None def get_request_pool( self, model_id: str, device_id: torch.device, pool_id: int @@ -539,19 +716,20 @@ def set_request_pool_map( request_pool: InferenceRequestPool, request_queue: mp.Queue, ): - """ - Set the request pool map for the given model_id, device and pool_id. - """ - if model_id not in self._request_pool_map: - self._request_pool_map[model_id] = {} - if device_id not in self._request_pool_map[model_id]: - self._request_pool_map[model_id][device_id] = PoolGroup(model_id) - self._request_pool_map[model_id][device_id].add_pool( - pool_id, request_pool, request_queue - ) - logger.info( - f"[Inference][{device_id}][Pool-{pool_id}] Registered pool for model {model_id}" - ) + with self._registry_lock: + """ + Set the request pool map for the given model_id, device and pool_id. + """ + if model_id not in self._request_pool_map: + self._request_pool_map[model_id] = {} + if device_id not in self._request_pool_map[model_id]: + self._request_pool_map[model_id][device_id] = PoolGroup(model_id) + self._request_pool_map[model_id][device_id].add_pool( + pool_id, request_pool, request_queue + ) + logger.info( + f"[Inference][{device_id}][Pool-{pool_id}] Registered pool for model {model_id}" + ) def get_load(self, model_id: str, device_id: torch.device, pool_id: int) -> int: """ @@ -562,19 +740,46 @@ def get_load(self, model_id: str, device_id: torch.device, pool_id: int) -> int: return pool_group.get_load(pool_id) return -1 - def stop(self): - self._stop_event.set() - - # shutdown pool controller - self._task_queue.put(None) - self._pool_control_worker_thread.join() - self._executor.close() - logger.info(f"PoolController stopped its task executor.") - - # shutdown pool instances - # TODO: pool instances can be shutdown in parallel - for inner in self._request_pool_map.values(): - for group in inner.values(): - group.shutdown() - - logger.info("The PoolController has been stopped.") + def begin_stop(self): + with self._registry_lock: + self._stop_event.set() + + @property + def stopping(self): + return self._stop_event.is_set() + + def stop(self, deadline): + self.begin_stop() + self._pool_control_worker_thread.join(max(0, deadline - time.monotonic())) + if self._pool_control_worker_thread.is_alive(): + raise RuntimeError("Model lifecycle thread did not exit") + self._executor.shutdown(wait=False, cancel_futures=True) + with self._registry_lock: + entries = [ + (pool_id, process, group.get_request_queue(pool_id), group) + for pool_id, (process, _, group) in self.pool_snapshot().items() + ] + processes = [process for _, process, _, _ in entries if process.pid is not None] + for process in processes: + if process.is_alive(): + process.terminate() + terminate_until = min(deadline, time.monotonic() + 2) + for process in processes: + process.join(max(0, terminate_until - time.monotonic())) + for process in processes: + if process.is_alive(): + process.kill() + for process in processes: + process.join(max(0, deadline - time.monotonic())) + if self._unconfirmed_start or any( + process.exitcode is None for process in processes + ): + raise RuntimeError("Could not confirm all model workers exited") + for pool_id, process, request_queue, group in entries: + _close_request_queue(request_queue, deadline) + with self._registry_lock: + group.remove_pool(pool_id) + process.close() + self._ready.pop(pool_id, None) + with self._registry_lock: + self._request_pool_map.clear() diff --git a/iotdb-core/ainode/iotdb/ainode/core/inference/pool_group.py b/iotdb-core/ainode/iotdb/ainode/core/inference/pool_group.py index b85f64d42cc4d..bf85470a8979d 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/inference/pool_group.py +++ b/iotdb-core/ainode/iotdb/ainode/core/inference/pool_group.py @@ -15,6 +15,7 @@ # specific language governing permissions and limitations # under the License. # +import threading from typing import Dict, Tuple import torch.multiprocessing as mp @@ -47,75 +48,91 @@ def __init__(self, model_id): self.pool_states: Dict[int, PoolState] = {} # structure: {pool_id: remaining_reqs_cnt} self.pool_remaining_reqs: Dict[int, AtomicInt] = {} + self._lock = threading.RLock() self.model_id = model_id self.request_dispatcher = BasicDispatcher(self.pool_states) def get_pool_group(self) -> Dict[int, Tuple[InferenceRequestPool, mp.Queue]]: - return self.pool_group + with self._lock: + return self.pool_group def add_pool( self, pool_id: int, request_pool: InferenceRequestPool, request_queue: mp.Queue ): - self.pool_group[pool_id] = (request_pool, request_queue) - self.pool_remaining_reqs[pool_id] = AtomicInt() + with self._lock: + self.pool_group[pool_id] = (request_pool, request_queue) + self.pool_remaining_reqs[pool_id] = AtomicInt() def remove_pool(self, pool_id: int): - self.pool_group.pop(pool_id, None) - self.pool_states.pop(pool_id, None) - self.pool_remaining_reqs.pop(pool_id, None) + with self._lock: + self.pool_group.pop(pool_id, None) + self.pool_states.pop(pool_id, None) + self.pool_remaining_reqs.pop(pool_id, None) def get_pool_ids(self) -> list[int]: - return list(self.pool_group.keys()) + with self._lock: + return list(self.pool_group.keys()) def get_pool_count(self) -> int: - return len(self.pool_group) + with self._lock: + return len(self.pool_group) def get_running_pool_count(self) -> int: - count = 0 - for _, state in self.pool_states.items(): - count += 1 if state == PoolState.RUNNING else 0 - return count + with self._lock: + count = 0 + for pool_id, state in self.pool_states.items(): + count += int( + state == PoolState.RUNNING + and self.pool_group[pool_id][0].is_alive() + ) + return count def dispatch_request( self, req: InferenceRequest, infer_proxy: InferenceRequestProxy ): - pool_id = self.request_dispatcher.dispatch_request(req, self.get_pool_ids()) - req_q = self.pool_group[pool_id][1] - self.pool_remaining_reqs[pool_id].increment_and_get() - infer_proxy.set_counter(self.pool_remaining_reqs[pool_id]) - req_q.put(req) - logger.debug( - f"[Inference][Pool-{pool_id}][Req-{req.req_id}] Request is queued for inference" - ) + with self._lock: + pool_id = self.request_dispatcher.dispatch_request(req, self.get_pool_ids()) + process, req_q = self.pool_group[pool_id] + if not process.is_alive(): + self.pool_states[pool_id] = PoolState.FAILED + raise InferenceModelInternalException("Inference worker is unavailable") + req.assigned_pool_id = pool_id + self.pool_remaining_reqs[pool_id].increment_and_get() + infer_proxy.set_counter(self.pool_remaining_reqs[pool_id]) + infer_proxy.assigned_pool_id = pool_id + req_q.put(req) + logger.debug( + f"[Inference][Pool-{pool_id}][Req-{req.req_id}] Request is queued for inference" + ) def get_request_pool(self, pool_id) -> InferenceRequestPool: - if pool_id not in self.pool_group: - raise InferenceModelInternalException( - f"[Inference][Pool-{pool_id}] Pool not found for model {self.model_id}" - ) - return self.pool_group[pool_id][0] + with self._lock: + if pool_id not in self.pool_group: + raise InferenceModelInternalException( + f"[Inference][Pool-{pool_id}] Pool not found for model {self.model_id}" + ) + return self.pool_group[pool_id][0] def get_request_queue(self, pool_id) -> mp.Queue: - if pool_id not in self.pool_group: - raise InferenceModelInternalException( - f"[Inference][Pool-{pool_id}] Pool not found for model {self.model_id}" - ) - return self.pool_group[pool_id][1] + with self._lock: + if pool_id not in self.pool_group: + raise InferenceModelInternalException( + f"[Inference][Pool-{pool_id}] Pool not found for model {self.model_id}" + ) + return self.pool_group[pool_id][1] def get_state(self, pool_id) -> PoolState: - return self.pool_states[pool_id] + with self._lock: + return self.pool_states[pool_id] def set_state(self, pool_id, state): - self.pool_states[pool_id] = state + with self._lock: + self.pool_states[pool_id] = state def get_load(self, pool_id) -> int: - """ - Currently, we use the number of remaining requests in the pool as the load estimation. - TODO: we will implement better load estimation in the future. - """ - return self.pool_remaining_reqs[pool_id].get() - - def shutdown(self): - for pool_id, (request_pool, _) in self.pool_group.items(): - logger.info(f"[Inference][Pool-{pool_id}] Shutting down the pool...") - request_pool.stop() + with self._lock: + """ + Currently, we use the number of remaining requests in the pool as the load estimation. + TODO: we will implement better load estimation in the future. + """ + return self.pool_remaining_reqs[pool_id].get() diff --git a/iotdb-core/ainode/iotdb/ainode/core/inference/utils.py b/iotdb-core/ainode/iotdb/ainode/core/inference/utils.py index d17f9fbcec536..70c7cb8b9ed52 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/inference/utils.py +++ b/iotdb-core/ainode/iotdb/ainode/core/inference/utils.py @@ -17,10 +17,31 @@ # import secrets import string +from numbers import Integral import torch +def parse_boolean_option(name: str, value: object) -> bool: + if isinstance(value, bool): + return value + if isinstance(value, str) and value.lower() in ("true", "false"): + return value.lower() == "true" + raise ValueError(f"{name} must be true or false.") + + +def parse_positive_integer_option(name: str, value: object) -> int: + if isinstance(value, (str, Integral)) and not isinstance(value, bool): + try: + number = int(value) + except ValueError: + pass + else: + if number > 0: + return number + raise ValueError(f"{name} must be a positive integer.") + + def generate_req_id(length=10, charset=string.ascii_letters + string.digits) -> str: """ Generate a random req_id string of specified length. diff --git a/iotdb-core/ainode/iotdb/ainode/core/manager/inference_manager.py b/iotdb-core/ainode/iotdb/ainode/core/manager/inference_manager.py index 426c5a2094381..2524261eb1472 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/manager/inference_manager.py +++ b/iotdb-core/ainode/iotdb/ainode/core/manager/inference_manager.py @@ -16,9 +16,14 @@ # under the License. # +import os import threading import time +from collections import deque +from concurrent.futures import Future +from functools import partial +import numpy as np import torch import torch.multiprocessing as mp @@ -31,6 +36,7 @@ from iotdb.ainode.core.inference.inference_request import ( InferenceRequest, InferenceRequestProxy, + InferenceResult, ) from iotdb.ainode.core.inference.pipeline.basic_pipeline import ( ChatPipeline, @@ -39,7 +45,7 @@ ) from iotdb.ainode.core.inference.pipeline.pipeline_loader import load_pipeline from iotdb.ainode.core.inference.pool_controller import PoolController -from iotdb.ainode.core.inference.utils import generate_req_id +from iotdb.ainode.core.inference.utils import generate_req_id, parse_boolean_option from iotdb.ainode.core.log import Logger from iotdb.ainode.core.manager.device_manager import DeviceManager from iotdb.ainode.core.manager.model_manager import ModelManager @@ -60,24 +66,60 @@ logger = Logger() +class _PoolRuntime: + def __init__(self): + self.queue = mp.get_context("spawn").Queue() + self.controller = PoolController(self.queue) + self.pending = {} + self.fault = None + self.receiver = None + self.retired = False + + class InferenceManager: - WAITING_INTERVAL_IN_MS = ( - AINodeDescriptor().get_config().get_ain_inference_batch_interval_in_ms() - ) # How often to check for requests in the result queue + _RECOVERY_DELAYS = (0.25, 1, 4) + _RECOVERY_WINDOW = 60 + _START_TIMEOUT = 300 + _RETIRE_TIMEOUT = 8 def __init__(self): self._model_manager = ModelManager() self._backend = DeviceManager() - self._result_queue = mp.Queue() - self._result_wrapper_map = {} self._result_wrapper_lock = threading.RLock() - self._stop_event = mp.Event() - self._result_handler_thread = threading.Thread( - target=self._handle_results, daemon=True + config = AINodeDescriptor().get_config() + self._inflight_slots = threading.BoundedSemaphore( + config.get_ain_inference_max_inflight() ) - self._result_handler_thread.start() - self._pool_controller = PoolController(self._result_queue) + self._accepting = True + # Legacy CPU fallback has one physical worker and no waiting queue. + self._cpu_slot = threading.BoundedSemaphore(1) + self._stopping = threading.Event() + self._wake_watchdog = threading.Event() + self._failed = False + self._candidate = None + self._restart_times = deque() + self._runtime = self._new_runtime() + self._watchdog_thread = threading.Thread( + target=self._watch_workers, daemon=True + ) + self._watchdog_thread.start() + + def _new_runtime(self): + runtime = _PoolRuntime() + runtime.receiver = threading.Thread( + target=self._handle_results, args=(runtime,), daemon=True + ) + runtime.receiver.start() + return runtime + + def _require_available(self, runtime=None): + if not self._accepting: + raise InferenceModelInternalException("AINode inference is unavailable") + if runtime is not None and runtime is not self._runtime: + raise InferenceModelInternalException( + "AINode workers changed; retry inference" + ) def load_model( self, existing_model_id: str, device_id_list: list[torch.device] @@ -90,22 +132,14 @@ def load_model( Returns: TSStatus: The status of the load model operation. """ - devices_to_be_processed: list[torch.device] = [] - devices_not_to_be_processed: list[torch.device] = [] - for device_id in device_id_list: - if self._pool_controller.has_request_pools( - model_id=existing_model_id, device_id=device_id - ): - devices_not_to_be_processed.append(device_id) - else: - devices_to_be_processed.append(device_id) - if len(devices_to_be_processed) > 0: - self._pool_controller.load_model( - model_id=existing_model_id, device_id_list=devices_to_be_processed - ) - logger.info( - f"[Inference] Start loading model [{existing_model_id}] to devices [{devices_to_be_processed}], skipped devices [{devices_not_to_be_processed}] cause they have already loaded this model." - ) + # Preserve command order even if a preceding UNLOAD is still queued. + # Idempotence is checked by the serialized lifecycle worker. + with self._result_wrapper_lock: + try: + self._require_available() + self._runtime.controller.load_model(existing_model_id, device_id_list) + except InferenceModelInternalException as error: + return get_status(TSStatusCode.LOAD_MODEL_ERROR, str(error)) return TSStatus( code=TSStatusCode.SUCCESS_STATUS.value, message='Successfully submitted load model task, please use "SHOW LOADED MODELS" to check progress.', @@ -114,22 +148,12 @@ def load_model( def unload_model( self, model_id: str, device_id_list: list[torch.device] ) -> TSStatus: - devices_to_be_processed = [] - devices_not_to_be_processed = [] - for device_id in device_id_list: - if self._pool_controller.has_request_pools( - model_id=model_id, device_id=device_id - ): - devices_to_be_processed.append(device_id) - else: - devices_not_to_be_processed.append(device_id) - if len(devices_to_be_processed) > 0: - self._pool_controller.unload_model( - model_id=model_id, device_id_list=device_id_list - ) - logger.info( - f"[Inference] Start unloading model [{model_id}] from devices [{devices_to_be_processed}], skipped devices [{devices_not_to_be_processed}] cause they haven't loaded this model." - ) + with self._result_wrapper_lock: + try: + self._require_available() + self._runtime.controller.unload_model(model_id, device_id_list) + except InferenceModelInternalException as error: + return get_status(TSStatusCode.UNLOAD_MODEL_ERROR, str(error)) return TSStatus( code=TSStatusCode.SUCCESS_STATUS.value, message='Successfully submitted unload model task, please use "SHOW LOADED MODELS" to check progress.', @@ -138,84 +162,272 @@ def unload_model( def show_loaded_models( self, device_id_list: list[torch.device] ) -> TShowLoadedModelsResp: - return TShowLoadedModelsResp( - status=get_status(TSStatusCode.SUCCESS_STATUS), - deviceLoadedModelsMap=self._pool_controller.show_loaded_models( - device_id_list - if len(device_id_list) > 0 - else self._backend.available_devices_with_cpu() - ), - ) + with self._result_wrapper_lock: + if not self._accepting: + return TShowLoadedModelsResp( + status=get_status( + TSStatusCode.AINODE_INTERNAL_ERROR, + "AINode inference is unavailable", + ) + ) + return TShowLoadedModelsResp( + status=get_status(TSStatusCode.SUCCESS_STATUS), + deviceLoadedModelsMap=self._runtime.controller.show_loaded_models( + device_id_list or self._backend.available_devices_with_cpu() + ), + ) + + def _finish_request(self, runtime, req_id, output=None, error=None, retiring=False): + with self._result_wrapper_lock: + if not retiring and (runtime is not self._runtime or not self._accepting): + return + entry = runtime.pending.pop(req_id, None) + if entry is None: + return + _, proxy, release = entry + try: + if error is not None: + proxy.set_exception(InferenceModelInternalException(str(error))) + else: + proxy.set_result(output) + finally: + release() + + def _record_fault(self, runtime, error): + with self._result_wrapper_lock: + if runtime.retired or self._stopping.is_set() or runtime.fault is not None: + return + runtime.fault = str(error) + runtime.controller.begin_stop() + if runtime is self._runtime: + self._accepting = False + self._wake_watchdog.set() - def _handle_results(self): - while not self._stop_event.is_set(): - if self._result_queue.empty(): - time.sleep(self.WAITING_INTERVAL_IN_MS / 1000) - continue - infer_req: InferenceRequest = self._result_queue.get() + def _check_workers(self): + with self._result_wrapper_lock: + if not self._accepting: + return + runtime = self._runtime + fault = runtime.controller.worker_fault() + grace = ( + AINodeDescriptor().get_config().get_ain_inference_timeout_grace_ms() + / 1000 + ) + now = time.monotonic() + if fault is None and any( + request.deadline is not None and now > request.deadline + grace + for request, _, _ in runtime.pending.values() + ): + fault = "Inference worker exceeded its deadline and grace period" + if fault is not None: + self._record_fault(runtime, fault) + + def _retire_runtime(self, runtime, reason): + if runtime.retired: + return + deadline = time.monotonic() + self._RETIRE_TIMEOUT + runtime.controller.stop(deadline) + runtime.queue._writer.close() + runtime.receiver.join(max(0, deadline - time.monotonic())) + if runtime.receiver.is_alive(): + raise RuntimeError("Inference result receiver did not exit") + runtime.queue._reader.close() + runtime.queue.close() + for req_id in list(runtime.pending): + self._finish_request(runtime, req_id, error=reason, retiring=True) + runtime.retired = True + + def _recover(self, old): + logger.error(f"Inference workers unavailable: {old.fault}") + desired, managed = old.controller.desired_residency() + self._retire_runtime(old, old.fault) + for attempt, delay in enumerate(self._RECOVERY_DELAYS, start=1): + if self._stopping.wait(delay): + return + now = time.monotonic() + while ( + self._restart_times + and now - self._restart_times[0] >= self._RECOVERY_WINDOW + ): + self._restart_times.popleft() + if len(self._restart_times) >= len(self._RECOVERY_DELAYS): + break + self._restart_times.append(now) with self._result_wrapper_lock: - self._result_wrapper_map[infer_req.req_id].set_result( - infer_req.get_final_output() + if self._stopping.is_set(): + return + self._candidate = candidate = self._new_runtime() + try: + candidate.controller.restore_residency( + desired, managed, time.monotonic() + self._START_TIMEOUT ) + with self._result_wrapper_lock: + if self._stopping.is_set(): + return + fault = candidate.fault or candidate.controller.worker_fault() + if fault is not None: + raise RuntimeError(fault) + self._runtime = candidate + self._candidate = None + self._accepting = True + logger.info(f"Inference workers restored on attempt {attempt}") + return + except Exception as error: + logger.error( + f"Inference worker recovery attempt {attempt} failed: {error}" + ) + self._retire_runtime(candidate, str(error)) + with self._result_wrapper_lock: + self._candidate = None + if not self._stopping.is_set(): + raise RuntimeError("Inference worker recovery budget exhausted") + + def _watch_workers(self): + while not self._stopping.is_set(): + self._wake_watchdog.wait(0.1) + self._wake_watchdog.clear() + try: + if not self._failed and not self._stopping.is_set(): + self._check_workers() + if self._runtime.fault is not None: + self._recover(self._runtime) + except Exception as error: + with self._result_wrapper_lock: + self._accepting = False + self._failed = True + logger.error(f"Inference workers remain unavailable: {error}") + for runtime in (self._runtime, self._candidate): + if runtime is not None: + try: + self._retire_runtime(runtime, "AINode is stopping") + except Exception as error: + logger.error( + f"Inference shutdown could not confirm cleanup: {error}" + ) - def _process_request(self, req): - req_id = req.req_id - infer_proxy = InferenceRequestProxy(req_id) + def _handle_results(self, runtime): + while True: + try: + infer_req = runtime.queue.get() + except Exception as error: + if not runtime.controller.stopping: + self._record_fault( + runtime, f"Inference result channel failed: {error}" + ) + return + try: + if isinstance(infer_req, tuple): + runtime.controller.mark_ready(*infer_req) + continue + output = ( + None + if infer_req.error is not None + else ( + infer_req.get_rpc_output() + if os.environ.get("AINODE_RESULT_FORMAT") == "numpy" + and isinstance(infer_req, InferenceResult) + else infer_req.get_final_output() + ) + ) + self._finish_request(runtime, infer_req.req_id, output, infer_req.error) + except Exception as error: + self._record_fault(runtime, f"Invalid inference result: {error}") + return + + def _admit(self): with self._result_wrapper_lock: - self._result_wrapper_map[req_id] = infer_proxy + self._require_available() + if not self._inflight_slots.acquire(blocking=False): + raise InferenceModelInternalException( + "AINode inference capacity is full; retry with backoff" + ) + return self._runtime + + def _submit_prepared( + self, runtime, model_id, deadline, make_request, cpu_args, release + ): + """Submit under the admission lock, returning a wait callable for use outside it.""" + owns_release = True try: - # dispatch request to the pool - self._pool_controller.add_request(req, infer_proxy) - outputs = infer_proxy.wait_for_result() - return outputs - except Exception as e: - logger.error(e) - raise InferenceModelInternalException(str(e)) + self._require_available(runtime) + if deadline is not None and time.monotonic() >= deadline: + raise TimeoutError("AINode inference deadline exceeded") + controller = runtime.controller + if controller.has_running_pools(model_id): + request = make_request() + proxy = InferenceRequestProxy(request.req_id) + if request.req_id in runtime.pending: + raise RuntimeError("Duplicate inference request ID") + runtime.pending[request.req_id] = (request, proxy, release) + try: + controller.add_request(request, proxy) + except BaseException: + runtime.pending.pop(request.req_id) + proxy.set_exception( + InferenceModelInternalException("Inference dispatch failed") + ) + raise + owns_release = False + return partial(proxy.wait_for_result, deadline) + if controller.requires_loaded_pool(model_id): + raise InferenceModelInternalException( + "Model is not ready; LOAD MODEL and check SHOW LOADED MODELS" + ) + if not self._cpu_slot.acquire(blocking=False): + raise InferenceModelInternalException("CPU inference worker is busy") + future = Future() + + def run_cpu(): + try: + try: + result = self._run_cpu(*cpu_args()) + finally: + self._cpu_slot.release() + release() + except BaseException as error: + future.set_exception(error) + else: + future.set_result(result) + + try: + threading.Thread(target=run_cpu, name="ainode-cpu", daemon=True).start() + except BaseException: + self._cpu_slot.release() + raise + + owns_release = False + return lambda: future.result( + timeout=( + None if deadline is None else max(0, deadline - time.monotonic()) + ) + ) finally: - with self._result_wrapper_lock: - del self._result_wrapper_map[req_id] + if owns_release: + release() - def _do_inference_and_construct_resp( - self, - model_id: str, - model_inputs, - inference_attrs: dict, - ) -> list[bytes]: - - if self._pool_controller.has_running_pools(model_id): - # Only forecast task can use pool - output_length = int(inference_attrs.get("output_length", 96)) - infer_req = InferenceRequest( - req_id=generate_req_id(), - model_id=model_id, - inputs=torch.stack([data["targets"] for data in model_inputs], dim=0), - output_length=output_length, + def _execute_prepared( + self, runtime, model_id, deadline, make_request, cpu_args, release + ): + with self._result_wrapper_lock: + wait = self._submit_prepared( + runtime, model_id, deadline, make_request, cpu_args, release ) - outputs = self._process_request(infer_req) + return wait() + + def _run_cpu(self, model_id, model_inputs, output_length, inference_attrs): + model_info = self._model_manager.get_model_info(model_id) + pipeline = load_pipeline(model_info, device=self._backend.torch_device("cpu")) + options = {"output_length": output_length, **inference_attrs} + inputs = pipeline.preprocess(model_inputs, **options) + if isinstance(pipeline, ForecastPipeline): + outputs = pipeline.forecast(inputs, **options) + elif isinstance(pipeline, ClassificationPipeline): + outputs = pipeline.classify(inputs, **options) + elif isinstance(pipeline, ChatPipeline): + outputs = pipeline.chat(inputs, **options) else: - model_info = self._model_manager.get_model_info(model_id) - inference_pipeline = load_pipeline( - model_info, device=self._backend.torch_device("cpu") - ) - inputs = inference_pipeline.preprocess(model_inputs, **inference_attrs) - if isinstance(inference_pipeline, ForecastPipeline): - outputs = inference_pipeline.forecast(inputs, **inference_attrs) - elif isinstance(inference_pipeline, ClassificationPipeline): - outputs = inference_pipeline.classify(inputs, **inference_attrs) - elif isinstance(inference_pipeline, ChatPipeline): - outputs = inference_pipeline.chat(inputs, **inference_attrs) - else: - outputs = None - logger.error("[Inference] Unsupported pipeline type.") - outputs = inference_pipeline.postprocess(outputs, **inference_attrs) - - # DataNode currently exposes inference outputs as DOUBLE, so serialize the - # physical TsBlock column as double even when model tensors are float32. - resp_list = [] - for output in outputs: - resp = convert_tensor_to_tsblock(output.to(dtype=torch.float64)) - resp_list.append(resp) - return resp_list + raise ValueError("Unsupported pipeline type") + return pipeline.postprocess(outputs, **options) def _max_output_length(self, model_id: str) -> int: """AINode's output_length limit, lowered to the model's own limit if it has one. @@ -241,25 +453,72 @@ def _run_forecast( single_batch: bool, ): model_id = req.modelId + owns_slot = False try: + runtime = self._admit() + owns_slot = True + release_slot = self._inflight_slots.release + started = time.monotonic() raw = data_getter(req) inputs = convert_tsblock_to_tensor(raw) inference_attrs = extract_attrs(req) - output_length = int(inference_attrs.get("output_length", 96)) + config = AINodeDescriptor().get_config() + configured_timeout = config.get_ain_inference_timeout_ms() + timeout_ms = min( + configured_timeout, + int(inference_attrs.pop("_ain_timeout_ms", configured_timeout)), + ) + if timeout_ms <= 0: + raise TimeoutError("AINode inference deadline exceeded") + deadline = started + timeout_ms / 1000 + output_length = int(inference_attrs.pop("output_length", 96)) max_output_length = self._max_output_length(model_id) if not 1 <= output_length <= max_output_length: raise NumericalRangeException( "output_length", output_length, 1, max_output_length ) - model_inputs: list[dict[str, torch.Tensor | dict[str, torch.Tensor]]] = [ - {"targets": inputs[0]} - ] + if "predict_batches_jointly" in inference_attrs: + inference_attrs["predict_batches_jointly"] = parse_boolean_option( + "predict_batches_jointly", + inference_attrs["predict_batches_jointly"], + ) + model_inputs_list = [{"targets": targets} for targets in inputs] + + def make_request(): + return InferenceRequest( + req_id=generate_req_id(), + model_id=model_id, + inputs=( + inputs if os.environ.get("AINODE_REUSE_INPUTS") == "1" else None + ), + model_inputs=model_inputs_list, + output_length=output_length, + inference_attrs={"output_length": output_length, **inference_attrs}, + _deadline=deadline, + ) - resp_list = self._do_inference_and_construct_resp( - model_id, model_inputs, inference_attrs + owns_slot = False + outputs = self._execute_prepared( + runtime, + model_id, + deadline, + make_request, + lambda: (model_id, model_inputs_list, output_length, inference_attrs), + release_slot, ) + if time.monotonic() >= deadline: + raise TimeoutError("AINode inference deadline exceeded") + + resp_list = [ + convert_tensor_to_tsblock( + output.astype(np.float64, copy=False) + if isinstance(output, np.ndarray) + else output.to(dtype=torch.float64) + ) + for output in outputs + ] return resp_cls( get_status(TSStatusCode.SUCCESS_STATUS), @@ -269,16 +528,18 @@ def _run_forecast( except Exception as e: logger.error(e) status = get_status(TSStatusCode.AINODE_INTERNAL_ERROR, str(e)) - empty = b"" if single_batch else [] - return resp_cls(status, empty) + return resp_cls(status, []) + finally: + if owns_slot: + release_slot() def forecast(self, req: TForecastReq): return self._run_forecast( req, data_getter=lambda r: r.inputData, extract_attrs=lambda r: { - "output_length": r.outputLength, **(r.options or {}), + "output_length": r.outputLength, }, resp_cls=TForecastResp, single_batch=True, @@ -292,18 +553,29 @@ def inference(self, req: TInferenceReq): "output_length": ( 96 if r.inferenceAttributes is None - else int(r.inferenceAttributes.pop("outputLength", 96)) + else int(r.inferenceAttributes.get("outputLength", 96)) ), - **(r.inferenceAttributes or {}), + **{ + key: value + for key, value in (r.inferenceAttributes or {}).items() + if key != "outputLength" + }, }, resp_cls=TInferenceResp, single_batch=False, ) + def begin_stop(self): + with self._result_wrapper_lock: + self._accepting = False + for runtime in (self._runtime, self._candidate): + if runtime is not None and not runtime.retired: + runtime.controller.begin_stop() + self._stopping.set() + self._wake_watchdog.set() + def stop(self): - self._stop_event.set() - self._pool_controller.stop() - while not self._result_queue.empty(): - self._result_queue.get_nowait() - self._result_queue.close() - logger.info("The Inference Manager has been stopped.") + self.begin_stop() + self._watchdog_thread.join(timeout=2 * self._RETIRE_TIMEOUT + 1) + if self._watchdog_thread.is_alive(): + logger.error("Inference shutdown timed out") diff --git a/iotdb-core/ainode/iotdb/ainode/core/manager/utils.py b/iotdb-core/ainode/iotdb/ainode/core/manager/utils.py index 892d4650e152d..ff71fce793c00 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/manager/utils.py +++ b/iotdb-core/ainode/iotdb/ainode/core/manager/utils.py @@ -42,7 +42,7 @@ def evaluate_system_resources(device: torch.device) -> dict: if device.type == "cuda": - free_mem, total_mem = torch.cuda.mem_get_info() + free_mem, total_mem = torch.cuda.mem_get_info(device) logger.info( f"[Inference][{device}] CUDA device memory: free={free_mem/1024**2:.2f} MB, total={total_mem/1024**2:.2f} MB" ) diff --git a/iotdb-core/ainode/iotdb/ainode/core/model/chronos2/pipeline_chronos2.py b/iotdb-core/ainode/iotdb/ainode/core/model/chronos2/pipeline_chronos2.py index 2d9cdf4fb2fe3..d5ac6dbbbdb98 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/model/chronos2/pipeline_chronos2.py +++ b/iotdb-core/ainode/iotdb/ainode/core/model/chronos2/pipeline_chronos2.py @@ -25,6 +25,7 @@ from torch.utils.data import DataLoader from iotdb.ainode.core.inference.pipeline.basic_pipeline import ForecastPipeline +from iotdb.ainode.core.inference.utils import parse_positive_integer_option from iotdb.ainode.core.log import Logger from iotdb.ainode.core.model.chronos2.dataset import Chronos2Dataset, DatasetMode from iotdb.ainode.core.model.chronos2.utils import ( @@ -36,6 +37,10 @@ class Chronos2Pipeline(ForecastPipeline): + supports_missing_values = True + # _predict_batch moves the host-prepared tensors to the model's device. + input_device = torch.device("cpu") + def __init__(self, model_info, **model_kwargs): super().__init__(model_info, **model_kwargs) @@ -258,8 +263,9 @@ def forecast(self, inputs, **infer_kwargs) -> list[torch.Tensor]: prediction_length = infer_kwargs.get("output_length", 96) # The maximum number of output patches to generate in a single forward pass before the long-horizon heuristic kicks in. Note: A value larger # than the model's default max_output_patches may lead to degradation in forecast accuracy, defaults to a model-specific value - max_output_patches = infer_kwargs.get( - "max_output_patches", self.max_output_patches + max_output_patches = parse_positive_integer_option( + "max_output_patches", + infer_kwargs.get("max_output_patches", self.max_output_patches), ) # The set of quantiles to use when making long-horizon predictions; must be a subset of the model's default quantiles. These quantiles # are appended to the historical context and input into the model autoregressively to generate long-horizon predictions. Note that the @@ -288,7 +294,10 @@ def forecast(self, inputs, **infer_kwargs) -> list[torch.Tensor]: # The maximum context length used during for inference, # by default set to the model's default context length - context_length = infer_kwargs.get("context_length", self.model_context_length) + context_length = parse_positive_integer_option( + "context_length", + infer_kwargs.get("context_length", self.model_context_length), + ) if context_length > self.model_context_length: logger.warning( f"The specified context_length {context_length} is greater than the model's default context length {self.model_context_length}. " @@ -299,7 +308,9 @@ def forecast(self, inputs, **infer_kwargs) -> list[torch.Tensor]: # The batch size used for prediction. # Note that the batch size here means the number of time series, # including target(s) and covariates,which are input into the model. - batch_size = infer_kwargs.get("batch_size", 256) + batch_size = parse_positive_integer_option( + "batch_size", infer_kwargs.get("batch_size", 256) + ) test_dataset = Chronos2Dataset.convert_inputs( inputs=inputs, diff --git a/iotdb-core/ainode/iotdb/ainode/core/model/fp32_execution.py b/iotdb-core/ainode/iotdb/ainode/core/model/fp32_execution.py new file mode 100644 index 0000000000000..f5719906b8503 --- /dev/null +++ b/iotdb-core/ainode/iotdb/ainode/core/model/fp32_execution.py @@ -0,0 +1,876 @@ +# 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 collections +import contextlib +import dataclasses +import dis +import importlib +import inspect +import os +import random +import sys +import threading +import time +import types +from dataclasses import dataclass + +import numpy +import torch + +_COMPILER_LOCK = threading.RLock() + + +@dataclass(frozen=True) +class ExecutionOptions: + compile: bool = False + max_static_bytes: int = 268435456 + max_segments: int = 32 + max_state_backup_bytes: int = 1073741824 + + def __post_init__(self): + if ( + self.max_static_bytes < 1 + or self.max_segments < 1 + or self.max_state_backup_bytes < 1 + ): + raise ValueError("execution limits must be positive") + + +class UnsupportedInput(Exception): + pass + + +class ModelStateMutation(RuntimeError): + pass + + +class ExecutionInstallError(Exception): + pass + + +def _key(value): + if isinstance(value, torch.Tensor): + if type(value) is not torch.Tensor: + raise UnsupportedInput("tensor subclass") + if value.layout != torch.strided or value.requires_grad: + raise UnsupportedInput("tensor layout or gradient") + if value.is_floating_point() and value.dtype != torch.float32: + raise UnsupportedInput("non-FP32 floating input") + if value.is_complex(): + raise UnsupportedInput("complex input") + return ( + "tensor", + tuple(value.shape), + tuple(value.stride()), + str(value.dtype), + str(value.device), + value.storage_offset(), + ) + if value is None or type(value) in (bool, int, str, bytes): + return (type(value).__name__, value) + if type(value) is float: + return ("float", value.hex()) + if type(value) in (tuple, list): + return (type(value).__name__, tuple(_key(item) for item in value)) + if type(value) is dict: + return ("dict", tuple((_key(k), _key(v)) for k, v in value.items())) + raise UnsupportedInput("unsupported argument type: " + type(value).__name__) + + +def _map_tensors(value, fn): + if isinstance(value, torch.Tensor): + return fn(value) + if type(value) is tuple: + return tuple(_map_tensors(item, fn) for item in value) + if type(value) is list: + return [_map_tensors(item, fn) for item in value] + if type(value) is dict: + return {key: _map_tensors(item, fn) for key, item in value.items()} + if value is None or type(value) in (bool, int, float, str, bytes): + return value + raise UnsupportedInput("unsupported argument type: " + type(value).__name__) + + +def _tensor_list(value): + tensors = [] + _map_tensors(value, lambda tensor: tensors.append(tensor) or tensor) + return tensors + + +def _no_alias(tensors): + seen = set() + for tensor in tensors: + identity = (str(tensor.device), tensor.untyped_storage().data_ptr()) + if identity in seen: + raise UnsupportedInput("aliased tensor storage") + seen.add(identity) + + +def _clone_inputs(args, kwargs, byte_limit): + tensors = _tensor_list((args, kwargs)) + _no_alias(tensors) + required = 0 + for tensor in tensors: + if tensor.is_conj() or tensor.is_neg(): + raise UnsupportedInput("conjugate or negative tensor view") + storage_size = tensor.storage_offset() + if tensor.numel(): + storage_size += 1 + sum( + (size - 1) * stride + for size, stride in zip(tensor.shape, tensor.stride()) + ) + required += storage_size * tensor.element_size() + if required > byte_limit: + raise UnsupportedInput("preparation input byte limit exceeded") + + def clone(tensor): + storage_size = tensor.storage_offset() + if tensor.numel(): + storage_size += 1 + sum( + (size - 1) * stride + for size, stride in zip(tensor.shape, tensor.stride()) + ) + storage = torch.empty(storage_size, dtype=tensor.dtype, device=tensor.device) + return storage.as_strided( + tensor.shape, tensor.stride(), tensor.storage_offset() + ).copy_(tensor) + + return _map_tensors((args, kwargs), clone) + + +def _assert_close(actual, expected): + if type(actual) is not type(expected): + raise AssertionError("output types differ") + if isinstance(actual, torch.Tensor): + torch.testing.assert_close( + actual, expected, rtol=1e-4, atol=1e-3, equal_nan=True + ) + elif dataclasses.is_dataclass(actual) and not isinstance(actual, type): + if any(not field.init for field in dataclasses.fields(actual)): + raise UnsupportedInput("dataclass output has non-init fields") + for field in dataclasses.fields(actual): + _assert_close(getattr(actual, field.name), getattr(expected, field.name)) + elif type(actual) in (tuple, list): + if len(actual) != len(expected): + raise AssertionError("output lengths differ") + for left, right in zip(actual, expected): + _assert_close(left, right) + elif type(actual) is dict: + if actual.keys() != expected.keys(): + raise AssertionError("output keys differ") + for key in actual: + _assert_close(actual[key], expected[key]) + elif actual is None or type(actual) in (bool, int, float, str, bytes): + if actual != expected: + raise AssertionError("output values differ") + else: + raise UnsupportedInput("unsupported output type: " + type(actual).__name__) + + +def _rng_snapshot(): + return ( + random.getstate(), + numpy.random.get_state(), + torch.random.get_rng_state(), + [ + torch.cuda.get_rng_state(device) + for device in range(torch.cuda.device_count()) + ], + ) + + +def _rng_equal(left, right): + return ( + left[0] == right[0] + and left[1][0] == right[1][0] + and numpy.array_equal(left[1][1], right[1][1]) + and left[1][2:] == right[1][2:] + and torch.equal(left[2], right[2]) + and len(left[3]) == len(right[3]) + and all(torch.equal(a, b) for a, b in zip(left[3], right[3])) + ) + + +def _audit_compiled_graph(graph): + random_names = ( + "rand", + "bernoulli", + "multinomial", + "normal", + "poisson", + "dropout", + "rrelu", + ) + identity_dropout_targets = ( + torch.nn.functional.dropout, + torch.nn.functional.dropout1d, + torch.nn.functional.dropout2d, + torch.nn.functional.dropout3d, + torch.nn.functional.alpha_dropout, + torch.nn.functional.feature_alpha_dropout, + ) + for node in graph.graph.nodes: + if node.op == "call_function": + name = getattr(node.target, "__name__", "").lower() + tags = getattr(node.target, "tags", ()) + identity_dropout = False + if any(node.target is target for target in identity_dropout_targets): + try: + arguments = inspect.signature(node.target).bind( + *node.args, **node.kwargs + ) + arguments.apply_defaults() + probability = arguments.arguments["p"] + training = arguments.arguments["training"] + inplace = arguments.arguments["inplace"] + identity_dropout = ( + type(training) is bool + and type(probability) in (int, float) + and 0 <= probability <= 1 + and inplace is False + and (training is False or probability == 0) + ) + except (TypeError, ValueError, KeyError): + pass + if not identity_dropout and ( + name.startswith(random_names) + or name in ("alpha_dropout", "feature_alpha_dropout") + or torch.Tag.nondeterministic_seeded in tags + ): + raise UnsupportedInput("random compiled operation: " + str(node.target)) + values = torch.utils._pytree.tree_leaves( + (node.args, node.kwargs, node.meta.get("example_value")) + ) + for value in values: + dtype = value.dtype if isinstance(value, torch.Tensor) else value + if isinstance(dtype, torch.dtype) and dtype in ( + torch.float16, + torch.bfloat16, + torch.float64, + ): + raise UnsupportedInput("non-FP32 compiled intermediate: " + str(dtype)) + + +@contextlib.contextmanager +def _preserve_rng(): + python_state = random.getstate() + numpy_state = numpy.random.get_state() + devices = ( + list(range(torch.cuda.device_count())) if torch.cuda.is_available() else [] + ) + try: + with torch.random.fork_rng(devices=devices): + yield + finally: + random.setstate(python_state) + numpy.random.set_state(numpy_state) + + +def configure_fp32(): + torch.set_float32_matmul_precision("highest") + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.backends.cuda.enable_flash_sdp(False) + torch.backends.cuda.enable_mem_efficient_sdp(False) + torch.backends.cuda.enable_cudnn_sdp(False) + torch.backends.cuda.enable_math_sdp(True) + + +def _fp32_enabled(): + return ( + torch.get_float32_matmul_precision() == "highest" + and not torch.backends.cuda.matmul.allow_tf32 + and not torch.backends.cudnn.allow_tf32 + and not torch.backends.cuda.flash_sdp_enabled() + and not torch.backends.cuda.mem_efficient_sdp_enabled() + and not torch.backends.cuda.cudnn_sdp_enabled() + and torch.backends.cuda.math_sdp_enabled() + and not torch.is_autocast_enabled() + and not torch.is_autocast_enabled("cpu") + and os.environ.get("TORCH_ALLOW_TF32_CUBLAS_OVERRIDE", "0") != "1" + ) + + +def _triton_fp32_state(load=False): + state = { + "environment": os.environ.get("TRITON_F32_DEFAULT"), + "effective": None, + "error": None, + } + try: + triton = sys.modules.get("triton") + if triton is None and load: + triton = importlib.import_module("triton") + if triton is None: + state["error"] = "Triton is not loaded" + else: + state["effective"] = triton.knobs.language.fp32_default + except Exception as error: + state["error"] = type(error).__name__ + ": " + str(error) + return state + + +def _require_triton_ieee(): + state = _triton_fp32_state(load=True) + if state["error"] or state["environment"] != "ieee" or state["effective"] != "ieee": + raise UnsupportedInput( + "Triton FP32 requires environment and effective knob ieee: " + repr(state) + ) + + +class FP32Execution: + def __init__(self, model, options): + self.model = model + self.options = options + self.original_forward = model.forward + try: + self.__signature__ = inspect.signature(self.original_forward) + except (TypeError, ValueError) as error: + raise ExecutionInstallError( + "forward signature cannot be preserved" + ) from error + self.__wrapped__ = self.original_forward + self.lock = threading.RLock() + self.entries = {} + self.failures = {} + self.stats = collections.Counter() + self.events = collections.deque(maxlen=64) + self.preparing = False + self.weight_dtypes = sorted({str(p.dtype) for p in model.parameters()}) + self.buffer_dtypes = sorted({str(p.dtype) for p in model.buffers()}) + self.input_dtypes = collections.Counter() + self.weight_dtype_counts = collections.Counter( + str(p.dtype) for p in model.parameters() + ) + self.buffer_dtype_counts = collections.Counter( + str(p.dtype) for p in model.buffers() + ) + self.inductor_options = {} + + def _event(self, stage, error): + self.stats[stage] += 1 + self.events.append( + {"stage": stage, "type": type(error).__name__, "message": str(error)} + ) + + def snapshot(self): + with self.lock: + return { + "counts": dict(self.stats), + "events": list(self.events), + "prepared_entries": len(self.entries), + "prepared_signatures": [repr(key) for key in self.entries], + "blacklisted_entries": len(self.failures), + "failed_signatures": [ + {"signature": repr(key), **details} + for key, details in self.failures.items() + ], + "weight_dtypes": self.weight_dtypes, + "buffer_dtypes": self.buffer_dtypes, + "input_dtype_counts": dict(self.input_dtypes), + "weight_dtype_counts": dict(self.weight_dtype_counts), + "buffer_dtype_counts": dict(self.buffer_dtype_counts), + "inductor_options": dict(self.inductor_options), + "precision": { + "matmul": torch.get_float32_matmul_precision(), + "cuda_allow_tf32": torch.backends.cuda.matmul.allow_tf32, + "cudnn_allow_tf32": torch.backends.cudnn.allow_tf32, + "flash_sdp": torch.backends.cuda.flash_sdp_enabled(), + "mem_efficient_sdp": torch.backends.cuda.mem_efficient_sdp_enabled(), + "cudnn_sdp": torch.backends.cuda.cudnn_sdp_enabled(), + "math_sdp": torch.backends.cuda.math_sdp_enabled(), + "tf32_override": os.environ.get("TORCH_ALLOW_TF32_CUBLAS_OVERRIDE"), + "triton_fp32_default": _triton_fp32_state(), + }, + "options": vars(self.options).copy(), + } + + def _eligible(self, args, kwargs): + if ( + not _fp32_enabled() + or torch.is_grad_enabled() + or any(module.training for module in self.model.modules()) + ): + raise UnsupportedInput("precision, grad mode, or model training state") + tensors = _tensor_list((args, kwargs)) + if len(tensors) > 256: + raise UnsupportedInput("too many input tensors") + self.input_dtypes.update(str(tensor.dtype) for tensor in tensors) + if not tensors or any(tensor.device.type != "cuda" for tensor in tensors): + raise UnsupportedInput("inputs must be CUDA tensors") + devices = {tensor.device for tensor in tensors} + for tensor in list(self.model.parameters()) + list(self.model.buffers()): + if tensor.device not in devices: + raise UnsupportedInput("model device differs from inputs") + if tensor.is_floating_point() and tensor.dtype != torch.float32: + raise UnsupportedInput("non-FP32 floating model state") + if tensor.is_complex(): + raise UnsupportedInput("complex model state") + if len(devices) != 1: + raise UnsupportedInput("multiple CUDA devices") + _require_triton_ieee() + return _key((args, kwargs)) + + def _check_preparation_code(self): + forbidden = { + "STORE_GLOBAL", + "DELETE_GLOBAL", + "STORE_ATTR", + "DELETE_ATTR", + "STORE_SUBSCR", + "DELETE_SUBSCR", + } + mutation_methods = { + "append", + "extend", + "insert", + "pop", + "remove", + "clear", + "update", + "setdefault", + "setattr", + "delattr", + } + for name, module in self.model.named_modules(): + if type(module).__call__ is not torch.nn.Module.__call__: + raise UnsupportedInput( + "preparation rejects custom module call: " + name + ) + for key, value in module.__dict__.items(): + if "hook" in key and value: + raise UnsupportedInput("preparation rejects module hooks: " + name) + function = self.original_forward if module is self.model else module.forward + function = getattr(function, "__func__", function) + if not isinstance(function, types.FunctionType): + raise UnsupportedInput("unauditable preparation forward: " + name) + pending = [function] + seen = set() + while pending: + function = pending.pop() + if function in seen: + continue + seen.add(function) + wrapped = getattr(function, "__wrapped__", None) + if isinstance(wrapped, types.FunctionType): + pending.append(wrapped) + instructions = list(dis.get_instructions(function)) + line = function.__code__.co_firstlineno + for index, instruction in enumerate(instructions): + line = instruction.starts_line or line + location = ( + f"module={name or ''} function={function.__qualname__} " + f"file={function.__code__.co_filename}:{line} opcode={instruction.opname}" + ) + if instruction.opname in forbidden or ( + instruction.opname in ("STORE_DEREF", "DELETE_DEREF") + and instruction.argval in function.__code__.co_freevars + ): + raise UnsupportedInput( + "preparation rejects Python write: " + location + ) + if instruction.opname == "IMPORT_NAME": + imported = sys.modules.get(instruction.argval) + prefix = instructions[max(0, index - 2) : index] + if ( + not isinstance(imported, types.ModuleType) + or len(prefix) != 2 + or any(item.opname != "LOAD_CONST" for item in prefix) + or prefix[0].argval != 0 + or ( + prefix[1].argval + and any( + item == "*" or item not in vars(imported) + for item in prefix[1].argval + ) + ) + ): + raise UnsupportedInput( + "preparation rejects unsafe import: " + location + ) + if instruction.opname in ( + "LOAD_METHOD", + "LOAD_ATTR", + "LOAD_GLOBAL", + ): + member = instruction.argval + if member in mutation_methods or ( + member.endswith("_") and not member.startswith("_") + ): + raise UnsupportedInput( + "preparation rejects possible mutation: " + + member + + " " + + location + ) + if ( + instruction.opname in ("LOAD_METHOD", "LOAD_ATTR") + and index + and instructions[index - 1].opname == "LOAD_FAST" + and instructions[index - 1].argval + == function.__code__.co_varnames[0] + ): + candidate = inspect.getattr_static( + type(module), member, None + ) + if isinstance(candidate, types.FunctionType): + pending.append(candidate) + + @contextlib.contextmanager + def _protect_model_state(self): + tensors = list(self.model.named_parameters()) + list(self.model.named_buffers()) + size = 0 + for name, tensor in tensors: + if tensor.layout != torch.strided or tensor.is_quantized: + raise UnsupportedInput("unsupported model state tensor: " + name) + if tensor.numel(): + span = 1 + sum( + (length - 1) * stride + for length, stride in zip(tensor.shape, tensor.stride()) + ) + size += max(tensor.numel(), span) * tensor.element_size() + if size > self.options.max_state_backup_bytes: + raise UnsupportedInput("model state backup byte limit exceeded") + backup = [] + for name, tensor in tensors: + try: + version = tensor._version + except RuntimeError as error: + raise UnsupportedInput("model state has no version counter") from error + metadata = ( + tensor.device, + tensor.stride(), + tensor.storage_offset(), + tensor.data_ptr(), + ) + backup.append( + (name, tensor, tensor.detach().to("cpu", copy=True), version, metadata) + ) + + def verify(): + current = list(self.model.named_parameters()) + list( + self.model.named_buffers() + ) + if len(current) != len(backup) or any( + name != saved_name or tensor is not saved_tensor + for (name, tensor), (saved_name, saved_tensor, _, _, _) in zip( + current, backup + ) + ): + raise RuntimeError("model state structure changed during preparation") + changed = [] + for name, tensor, saved, version, metadata in backup: + if ( + tensor.shape != saved.shape + or tensor.dtype != saved.dtype + or ( + tensor.device, + tensor.stride(), + tensor.storage_offset(), + tensor.data_ptr(), + ) + != metadata + ): + raise RuntimeError( + "model state metadata changed during preparation: " + name + ) + value = tensor.detach().to("cpu", copy=True) + value_changed = not torch.equal( + value.contiguous().reshape(-1).view(torch.uint8), + saved.contiguous().reshape(-1).view(torch.uint8), + ) + if value_changed or tensor._version != version: + changed.append((name, tensor, saved, value_changed)) + if changed: + with torch.no_grad(): + for _, tensor, saved, value_changed in changed: + if value_changed: + tensor.copy_(saved) + error = ModelStateMutation( + "model tensor state changed during preparation: " + + ", ".join(name for name, _, _, _ in changed) + ) + self._event("state_mutation", error) + raise error + + try: + yield verify + except ModelStateMutation: + raise + except BaseException: + try: + verify() + except ModelStateMutation: + pass + raise + else: + verify() + + def _blacklist(self, key, stage, error): + self._event(stage, error) + self.failures[key] = { + "stage": stage, + "type": type(error).__name__, + "message": str(error), + } + + def _compile(self): + import torch._inductor + + options = dict(torch._inductor.list_mode_options("default", dynamic=False)) + options.update( + { + "triton.cudagraphs": False, + "use_fast_math": False, + "cuda.use_fast_math": False, + "compile_threads": 1, + "force_disable_caches": True, + } + ) + owner = self + segment_count = 0 + + def backend(graph, inputs): + nonlocal segment_count + _require_triton_ieee() + if segment_count >= owner.options.max_segments: + raise UnsupportedInput("compiled segment limit exceeded") + segment_count += 1 + owner.stats["compiler_graphs"] += 1 + _audit_compiled_graph(graph) + with torch._inductor.config.patch(options): + effective = {} + for name in options: + value = torch._inductor.config + for part in name.split("."): + value = getattr(value, part) + effective[name] = value + if any(effective[name] != options[name] for name in effective): + raise UnsupportedInput( + "Inductor precision/options override: " + str(effective) + ) + owner.inductor_options = effective + compiled_graph = torch._inductor.compile(graph, inputs, options=options) + _require_triton_ieee() + owner.stats["compiled_segments_built"] += 1 + + def tracked(*args): + try: + _require_triton_ieee() + except UnsupportedInput as error: + owner._event("triton_precision_error", error) + raise + owner.stats["compiled_segment_executions"] += 1 + return compiled_graph(*args) + + return tracked + + start = time.perf_counter() + try: + compiled = torch.compile( + self.original_forward, backend=backend, fullgraph=False, dynamic=False + ) + except Exception as error: + self._event("compile_construction_error", error) + raise + finally: + self.stats["compile_construction_seconds"] += time.perf_counter() - start + self.stats["compiled_objects"] += 1 + return compiled + + def _prepare_one(self, key, args, kwargs): + if key in self.entries or key in self.failures: + return + if self.entries or self.failures: + self.stats["admission_full"] += 1 + return + try: + self._check_preparation_code() + with self._protect_model_state() as verify_state: + self._prepare_guarded(key, args, kwargs, verify_state) + except UnsupportedInput as error: + self.entries.pop(key, None) + self._blacklist(key, "admission_rejected", error) + + def _prepare_guarded(self, key, args, kwargs, verify_state): + started = time.perf_counter() + try: + reference_args, reference_kwargs = _clone_inputs( + args, kwargs, self.options.max_static_bytes + ) + candidate_args, candidate_kwargs = _clone_inputs( + args, kwargs, self.options.max_static_bytes + ) + except UnsupportedInput as error: + self._blacklist(key, "admission_rejected", error) + return + with _preserve_rng(): + reference = self._state_checked_call( + verify_state, self.original_forward, *reference_args, **reference_kwargs + ) + reference_rng = _rng_snapshot() + try: + compiled = self._compile() + except Exception as error: + self._blacklist(key, "compile_failure", error) + else: + compile_started = time.perf_counter() + try: + before = self.stats["compiler_graphs"] + executed_before = self.stats["compiled_segment_executions"] + breaks_before = dict(torch._dynamo.utils.counters["graph_break"]) + with _preserve_rng(), torch._dynamo.config.patch(suppress_errors=False): + actual = self._state_checked_call( + verify_state, compiled, *candidate_args, **candidate_kwargs + ) + compiled_rng = _rng_snapshot() + if ( + self.stats["compiler_graphs"] == before + or self.stats["compiled_segment_executions"] == executed_before + ): + raise UnsupportedInput("no compiled segment executed") + for reason, count in torch._dynamo.utils.counters[ + "graph_break" + ].items(): + delta = count - breaks_before.get(reason, 0) + if delta: + self.stats["graph_breaks"] += delta + self.events.append( + { + "stage": "graph_break", + "type": "GraphBreak", + "message": str(reason), + "count": delta, + } + ) + _assert_close(actual, reference) + if not _rng_equal(reference_rng, compiled_rng): + raise UnsupportedInput( + "compiled RNG progression differs from eager" + ) + except ( + torch._dynamo.exc.BackendCompilerFailed, + torch._dynamo.exc.Unsupported, + UnsupportedInput, + AssertionError, + ) as error: + if isinstance(error, torch._dynamo.exc.Unsupported): + self.stats["graph_break_or_unsupported"] += 1 + self._blacklist(key, "compile_failure", error) + else: + self.entries[key] = compiled + self.stats["compile_success"] += 1 + finally: + self.stats["compile_first_call_seconds"] += ( + time.perf_counter() - compile_started + ) + self.stats["prepare_seconds"] += time.perf_counter() - started + + @staticmethod + def _state_checked_call(verify_state, function, *args, **kwargs): + try: + result = function(*args, **kwargs) + except BaseException: + try: + verify_state() + except ModelStateMutation: + pass + raise + verify_state() + return result + + @contextlib.contextmanager + def prepare_calls(self): + with self.lock, _COMPILER_LOCK, _preserve_rng(): + if self.preparing: + raise RuntimeError("nested prepare_calls is unsupported") + self.preparing = True + try: + yield self + finally: + self.preparing = False + + def prepare_forward(self, *args, **kwargs): + with self.prepare_calls(): + return self(*args, **kwargs) + + def __call__(self, *args, **kwargs): + with self.lock: + self.stats["calls"] += 1 + if not self.preparing and _fp32_enabled() and not torch.is_grad_enabled(): + missing = False + try: + tensors = _tensor_list((args, kwargs)) + if ( + tensors + and len(tensors) <= 256 + and all(tensor.device.type == "cuda" for tensor in tensors) + ): + key = _key((args, kwargs)) + missing = key not in self.entries + except UnsupportedInput: + pass + if missing: + self.input_dtypes.update(str(tensor.dtype) for tensor in tensors) + self.stats["online_calls"] += 1 + self.stats["cache_miss"] += 1 + return self.original_forward(*args, **kwargs) + try: + key = self._eligible(args, kwargs) + except UnsupportedInput as error: + if not self.preparing: + self.stats["online_calls"] += 1 + self._event("ineligible", error) + return self.original_forward(*args, **kwargs) + if self.preparing: + self._prepare_one(key, args, kwargs) + return self.original_forward(*args, **kwargs) + self.stats["online_calls"] += 1 + compiled = self.entries.get(key) + if compiled is None: + self.stats["cache_miss"] += 1 + return self.original_forward(*args, **kwargs) + self.stats["cache_hit"] += 1 + before = self.stats["compiled_segment_executions"] + with _COMPILER_LOCK, torch.compiler.set_stance("eager_on_recompile"): + result = compiled(*args, **kwargs) + if self.stats["compiled_segment_executions"] > before: + self.stats["compiled_calls"] += 1 + else: + self.stats["compiled_guard_eager_calls"] += 1 + return result + + +def install_fp32_execution(model, options): + if not options.compile: + return None + configure_fp32() + execution = FP32Execution(model, options) + try: + model.forward = execution + if model.forward is not execution: + raise TypeError("forward replacement was not retained") + model._ainode_execution = execution + except (AttributeError, RuntimeError, TypeError) as error: + execution._event("installation_failure", error) + try: + model.forward = execution.original_forward + except (AttributeError, RuntimeError, TypeError): + pass + raise ExecutionInstallError(f"{type(error).__name__}: {error}") from error + return execution diff --git a/iotdb-core/ainode/iotdb/ainode/core/model/model_loader.py b/iotdb-core/ainode/iotdb/ainode/core/model/model_loader.py index 2476a05856d3e..76e19b9509854 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/model/model_loader.py +++ b/iotdb-core/ainode/iotdb/ainode/core/model/model_loader.py @@ -38,15 +38,52 @@ def load_model(model_info: ModelInfo, **model_kwargs) -> Any: - if model_info.auto_map is not None: + use_fp32 = False + if model_info.model_type != "sktime": + candidates = { + candidate.strip() + for candidate in os.environ.get("AINODE_FP32_EXECUTION", "").split(",") + if candidate.strip() + } + unknown = candidates - {"compile"} + if unknown: + raise ValueError(f"Unknown FP32 execution candidates: {sorted(unknown)}") + use_fp32 = "compile" in candidates + + if model_info.model_type == "sktime": + model = create_sktime_model(model_info.model_id) + elif model_info.auto_map is not None: model = load_transformers_model(model_info, **model_kwargs) - elif model_info.hub_mixin_cls is not None: + elif model_info.hub_mixin_cls: model = _load_hub_mixin_model(model_info, **model_kwargs) else: - if model_info.model_type == "sktime": - model = create_sktime_model(model_info.model_id) - else: - model = _load_torchscript_model(model_info, **model_kwargs) + if use_fp32: + model_kwargs["acceleration"] = False + model = _load_torchscript_model(model_info, **model_kwargs) + if use_fp32: + model = BACKEND.move_model(model, model_kwargs.get("device_map", "cpu")) + + if use_fp32: + from iotdb.ainode.core.model.fp32_execution import ( + ExecutionInstallError, + ExecutionOptions, + install_fp32_execution, + ) + + options = ExecutionOptions( + compile=True, + max_static_bytes=int( + os.environ.get("AINODE_FP32_MAX_STATIC_BYTES", "268435456") + ), + max_segments=int(os.environ.get("AINODE_FP32_MAX_SEGMENTS", "32")), + max_state_backup_bytes=int( + os.environ.get("AINODE_FP32_MAX_STATE_BACKUP_BYTES", "1073741824") + ), + ) + try: + install_fp32_execution(model, options) + except ExecutionInstallError as error: + logger.warning(f"FP32 execution installation unsupported: {error}") logger.info( f"Model {model_info.model_id} loaded to device {next(model.parameters()).device if model_info.model_type != 'sktime' else 'cpu'} successfully." @@ -101,10 +138,10 @@ def _load_torchscript_model(model_info: ModelInfo, **kwargs): logger.error(f"Model file not found at {model_file}.") raise ModelNotExistException(model_file) model = torch.jit.load(model_file) - if isinstance(model, torch._dynamo.eval_frame.OptimizedModule) or not acceleration: + if not acceleration or isinstance(model, torch._dynamo.eval_frame.OptimizedModule): return model try: model = torch.compile(model) - except Exception as e: - logger.warning(f"acceleration failed, fallback to normal mode: {str(e)}") + except Exception as error: + logger.warning(f"acceleration failed, fallback to normal mode: {error}") return BACKEND.move_model(model, device_map) diff --git a/iotdb-core/ainode/iotdb/ainode/core/model/sundial/pipeline_sundial.py b/iotdb-core/ainode/iotdb/ainode/core/model/sundial/pipeline_sundial.py index 8e4ffefe3164c..eb96c06e79961 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/model/sundial/pipeline_sundial.py +++ b/iotdb-core/ainode/iotdb/ainode/core/model/sundial/pipeline_sundial.py @@ -20,6 +20,10 @@ from iotdb.ainode.core.exception import InferenceModelInternalException from iotdb.ainode.core.inference.pipeline.basic_pipeline import ForecastPipeline +from iotdb.ainode.core.inference.utils import ( + parse_boolean_option, + parse_positive_integer_option, +) from iotdb.ainode.core.log import Logger from iotdb.ainode.core.model.model_info import ModelInfo @@ -81,8 +85,10 @@ def forecast(self, inputs: torch.Tensor, **infer_kwargs) -> torch.Tensor: torch.Tensor: A tensor containing the forecasted outputs with shape [batch_size, num_samples, output_length]. """ output_length = infer_kwargs.get("output_length", 96) - num_samples = infer_kwargs.get("num_samples", 10) - revin = infer_kwargs.get("revin", True) + num_samples = parse_positive_integer_option( + "num_samples", infer_kwargs.get("num_samples", 10) + ) + revin = parse_boolean_option("revin", infer_kwargs.get("revin", True)) outputs = self.model.generate( inputs, diff --git a/iotdb-core/ainode/iotdb/ainode/core/model/timer_xl/pipeline_timer.py b/iotdb-core/ainode/iotdb/ainode/core/model/timer_xl/pipeline_timer.py index 3b7957259d651..17d8f7281766f 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/model/timer_xl/pipeline_timer.py +++ b/iotdb-core/ainode/iotdb/ainode/core/model/timer_xl/pipeline_timer.py @@ -20,6 +20,7 @@ from iotdb.ainode.core.exception import InferenceModelInternalException from iotdb.ainode.core.inference.pipeline.basic_pipeline import ForecastPipeline +from iotdb.ainode.core.inference.utils import parse_boolean_option from iotdb.ainode.core.log import Logger from iotdb.ainode.core.model.model_info import ModelInfo @@ -80,7 +81,7 @@ def forecast(self, inputs: torch.Tensor, **infer_kwargs) -> torch.Tensor: torch.Tensor: A tensor containing the forecasted outputs, with shape [batch_size, output_length]. """ output_length = infer_kwargs.get("output_length", 96) - revin = infer_kwargs.get("revin", True) + revin = parse_boolean_option("revin", infer_kwargs.get("revin", True)) outputs = self.model.generate(inputs, max_new_tokens=output_length, revin=revin) return outputs diff --git a/iotdb-core/ainode/iotdb/ainode/core/model/toto/pipeline_toto.py b/iotdb-core/ainode/iotdb/ainode/core/model/toto/pipeline_toto.py index c6778a5e90bb6..4bf17ca53aee3 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/model/toto/pipeline_toto.py +++ b/iotdb-core/ainode/iotdb/ainode/core/model/toto/pipeline_toto.py @@ -19,6 +19,7 @@ import torch from iotdb.ainode.core.inference.pipeline.basic_pipeline import ForecastPipeline +from iotdb.ainode.core.inference.utils import parse_positive_integer_option from iotdb.ainode.core.log import Logger from iotdb.ainode.core.model.toto.data.util.dataset import MaskedTimeseries from iotdb.ainode.core.model.toto.inference.forecaster import TotoForecaster @@ -27,6 +28,8 @@ class TotoPipeline(ForecastPipeline): + supports_missing_values = True + """ Inference pipeline for the Toto time series foundation model. @@ -112,7 +115,11 @@ def _preprocess(self, inputs, **infer_kwargs): def forecast(self, inputs, **infer_kwargs) -> list[torch.Tensor]: output_length = infer_kwargs.get("output_length", 96) num_samples = infer_kwargs.get("num_samples", None) - samples_per_batch = infer_kwargs.get("samples_per_batch", 10) + if num_samples is not None: + num_samples = parse_positive_integer_option("num_samples", num_samples) + samples_per_batch = parse_positive_integer_option( + "samples_per_batch", infer_kwargs.get("samples_per_batch", 10) + ) forecaster = self._get_forecaster() diff --git a/iotdb-core/ainode/iotdb/ainode/core/rpc/client.py b/iotdb-core/ainode/iotdb/ainode/core/rpc/client.py index 81bb81d50bb34..79bd711c62da9 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/rpc/client.py +++ b/iotdb-core/ainode/iotdb/ainode/core/rpc/client.py @@ -24,6 +24,7 @@ from iotdb.ainode.core.config import AINodeDescriptor from iotdb.ainode.core.constant import TSStatusCode from iotdb.ainode.core.log import Logger +from iotdb.ainode.core.rpc.framed_transport import BoundedFramedTransport from iotdb.ainode.core.rpc.status import verify_success from iotdb.ainode.core.util.decorator import singleton from iotdb.thrift.common.ttypes import ( @@ -133,7 +134,9 @@ def _connect(self, target_config_node: TEndPoint) -> None: ) else: socket = TSocket.TSocket(target_config_node.ip, target_config_node.port) - transport = TTransport.TFramedTransport(socket) + config = AINodeDescriptor().get_config() + max_frame_size = config.get_ain_config_node_max_frame_size() + transport = BoundedFramedTransport(socket, max_frame_size) if not transport.isOpen(): try: transport.open() @@ -141,10 +144,14 @@ def _connect(self, target_config_node: TEndPoint) -> None: logger.error("TTransportException: {}".format(e)) raise e - if AINodeDescriptor().get_config().get_ain_thrift_compression_enabled(): - protocol = TCompactProtocol.TCompactProtocol(transport) + if config.get_ain_thrift_compression_enabled(): + protocol = TCompactProtocol.TCompactProtocol( + transport, string_length_limit=max_frame_size + ) else: - protocol = TBinaryProtocol.TBinaryProtocol(transport) + protocol = TBinaryProtocol.TBinaryProtocol( + transport, string_length_limit=max_frame_size + ) self._client = IConfigNodeRPCService.Client(protocol) def _wait_and_reconnect(self) -> None: diff --git a/iotdb-core/ainode/iotdb/ainode/core/rpc/framed_transport.py b/iotdb-core/ainode/iotdb/ainode/core/rpc/framed_transport.py new file mode 100644 index 0000000000000..dcbce06abf0c5 --- /dev/null +++ b/iotdb-core/ainode/iotdb/ainode/core/rpc/framed_transport.py @@ -0,0 +1,75 @@ +# 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. +# +from io import BytesIO +from struct import unpack + +from thrift.transport import TTransport + + +class BoundedFramedTransport(TTransport.TFramedTransport): + def __init__(self, transport, max_frame_size): + if not 0 < max_frame_size <= 0x3FFFFFFF: + raise ValueError("max_frame_size must be between 1 and 1073741823") + super().__init__(transport) + self._transport = transport + self._max_frame_size = max_frame_size + self._read_buffer = BytesIO() + + def read(self, size): + value = self._read_buffer.read(size) + if value: + return value + self.readFrame() + return self._read_buffer.read(size) + + def readFrame(self): + size = unpack("!i", self._transport.readAll(4))[0] + if size < 0: + raise TTransport.TTransportException( + TTransport.TTransportException.NEGATIVE_SIZE, + "Read a negative frame size ({})".format(size), + ) + if size > self._max_frame_size: + raise TTransport.TTransportException( + TTransport.TTransportException.SIZE_LIMIT, + "Frame size ({}) larger than the maximum ({})".format( + size, self._max_frame_size + ), + ) + self._read_buffer = BytesIO(self._transport.readAll(size)) + + @property + def cstringio_buf(self): + return self._read_buffer + + def cstringio_refill(self, prefix, required_length): + while len(prefix) < required_length: + self.readFrame() + prefix += self._read_buffer.getvalue() + self._read_buffer = BytesIO(prefix) + return self._read_buffer + + +class BoundedFramedTransportFactory(TTransport.TTransportFactoryBase): + def __init__(self, max_frame_size): + if not 0 < max_frame_size <= 0x3FFFFFFF: + raise ValueError("max_frame_size must be between 1 and 1073741823") + self.max_frame_size = max_frame_size + + def getTransport(self, transport): + return BoundedFramedTransport(transport, self.max_frame_size) diff --git a/iotdb-core/ainode/iotdb/ainode/core/rpc/handler.py b/iotdb-core/ainode/iotdb/ainode/core/rpc/handler.py index e3b5b49e05760..40eaf9543dde8 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/rpc/handler.py +++ b/iotdb-core/ainode/iotdb/ainode/core/rpc/handler.py @@ -57,6 +57,9 @@ def __init__(self, ainode): # ==================== Cluster Management ==================== + def begin_stop(self): + self._inference_manager.begin_stop() + def stop(self): logger.info("Stopping the RPC handler of IoTDB-AINode...") self._inference_manager.stop() diff --git a/iotdb-core/ainode/iotdb/ainode/core/rpc/process_frontend.py b/iotdb-core/ainode/iotdb/ainode/core/rpc/process_frontend.py new file mode 100644 index 0000000000000..7eab093364dcf --- /dev/null +++ b/iotdb-core/ainode/iotdb/ainode/core/rpc/process_frontend.py @@ -0,0 +1,489 @@ +# 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. +# + + +"""Opt-in CPU frontend processes with one authoritative model/backend owner.""" +import functools +import multiprocessing as mp +import os +import socket +import tempfile +import threading +import time +from multiprocessing.managers import BaseManager + +import numpy as np +import torch + +from iotdb.ainode.core.config import AINodeDescriptor +from iotdb.ainode.core.constant import TSStatusCode +from iotdb.ainode.core.exception import InferenceModelInternalException +from iotdb.ainode.core.inference.inference_request import InferenceRequestTransfer +from iotdb.ainode.core.log import Logger +from iotdb.ainode.core.manager.inference_manager import InferenceManager +from iotdb.ainode.core.rpc.status import get_status +from iotdb.thrift.ainode.ttypes import TForecastResp, TInferenceResp + +logger = Logger() + + +class LeaseRegistry: + """Exactly-once admission; frontend death never releases running backend work.""" + + def __init__(self, capacity): + self.capacity = capacity + self.lock = threading.RLock() + self.leases = {} + + def acquire(self, key, owner, runtime=None): + with self.lock: + if key in self.leases or len(self.leases) >= self.capacity: + return False + self.leases[key] = (owner, False, runtime) + return True + + def transfer(self, key, runtime=None): + with self.lock: + lease = self.leases.get(key) + if lease is None: + raise RuntimeError("Unknown backend admission lease") + owner, active, admitted_runtime = lease + if active: + raise RuntimeError("Duplicate backend submission") + if admitted_runtime is not runtime: + raise RuntimeError("AINode workers changed; retry inference") + self.leases[key] = (owner, True, runtime) + + def release(self, key, backend_done=False): + with self.lock: + lease = self.leases.get(key) + if lease is not None and (not lease[1] or backend_done): + self.leases.pop(key) + return True + return False + + def reap(self, owner): + with self.lock: + for key, (pid, active, _) in list(self.leases.items()): + if pid == owner and not active: + self.leases.pop(key) + + +def _arrays(value): + if isinstance(value, torch.Tensor): + return value.detach().cpu().numpy() + if isinstance(value, list): + return [_arrays(item) for item in value] + if isinstance(value, tuple): + return tuple(_arrays(item) for item in value) + return value + + +class BackendBroker: + def __init__(self, handler): + self.handler = handler + self.manager = handler._inference_manager + config = AINodeDescriptor().get_config() + self.admission = LeaseRegistry(config.get_ain_inference_max_inflight()) + self.max_clients = config.get_ain_rpc_max_concurrent_client_num() + self.connections = {} + self.lock = threading.RLock() + + def prepare(self, model_id, key, owner): + status = self.handler._ensure_model_is_registered(model_id) + if status.code != 200: + return status, False, None + with self.manager._result_wrapper_lock: + try: + self.manager._require_available() + except InferenceModelInternalException as error: + return ( + get_status(TSStatusCode.AINODE_INTERNAL_ERROR, str(error)), + False, + None, + ) + limit = self.manager._max_output_length(model_id) + admitted = self.admission.acquire(key, owner, self.manager._runtime) + return status, admitted, limit + + def abandon(self, key): + return self.admission.release(key) + + def infer(self, key, request): + if isinstance(request, InferenceRequestTransfer): + request = request.into_request() + + def cpu_args(): + request.restore_cpu_payload() + attrs = { + key: value + for key, value in request.inference_attrs.items() + if key != "output_length" + } + return request.model_id, request.model_inputs, request.output_length, attrs + + with self.manager._result_wrapper_lock: + runtime = self.manager._runtime + try: + self.manager._require_available() + model_id = request.model_id + deadline = request.deadline + self.admission.transfer(key, runtime) + except BaseException: + self.admission.release(key) + raise + wait = self.manager._submit_prepared( + runtime, + model_id, + deadline, + lambda: request, + cpu_args, + functools.partial(self.admission.release, key, backend_done=True), + ) + return _arrays(wait()) + + def call(self, name, args, kwargs): + if name.startswith("_") or name in ( + "forecast", + "inference", + "begin_stop", + "stop", + ): + raise ValueError("Unsupported management method") + return getattr(self.handler, name)(*args, **kwargs) + + def connection(self, owner, opening): + with self.lock: + count = self.connections.get(owner, 0) + if opening: + if sum(self.connections.values()) >= self.max_clients: + return False + self.connections[owner] = count + 1 + elif count: + self.connections[owner] = count - 1 + return True + + def reap(self, owner): + self.admission.reap(owner) + with self.lock: + self.connections.pop(owner, None) + + +class _BrokerManager(BaseManager): + pass + + +class _Admission: + def __init__(self, broker): + self.broker = broker + self.local = threading.local() + + def prepare(self, model_id): + key = os.urandom(16).hex() + self.local.key = key + self.local.claimed = False + status, admitted, limit = self.broker.prepare(model_id, key, os.getpid()) + self.local.admitted = admitted + self.local.output_length_limit = limit + return status + + def acquire(self, blocking=False): + self.local.claimed = True + return self.local.admitted + + @property + def release(self): + return functools.partial(self.broker.abandon, self.local.key) + + +class FrontendInferenceManager(InferenceManager): + def __init__(self, broker): + self._accepting = True + self._inflight_slots = _Admission(broker) + self._broker = broker + + def _admit(self): + self._require_available() + if not self._inflight_slots.acquire(): + raise InferenceModelInternalException( + "AINode inference capacity is full; retry with backoff" + ) + return None + + def _max_output_length(self, model_id: str) -> int: + return self._inflight_slots.local.output_length_limit + + def _execute_prepared( + self, runtime, model_id, deadline, make_request, cpu_args, release + ): + key = self._inflight_slots.local.key + try: + if time.monotonic() >= deadline: + raise TimeoutError("AINode inference deadline exceeded") + return self._broker.infer( + key, InferenceRequestTransfer.from_request(make_request()) + ) + except BaseException: + try: + release() + except Exception: + pass + raise + + def begin_stop(self): + self._accepting = False + + def stop(self): + self.begin_stop() + + +class _FrontendHandler: + def __init__(self, broker): + self.broker = broker + self.manager = FrontendInferenceManager(broker) + + def _run(self, name, req, response): + admission = self.manager._inflight_slots + status = admission.prepare(req.modelId) + if status.code != 200: + return response(status, b"" if name == "forecast" else []) + try: + return getattr(self.manager, name)(req) + finally: + if not admission.local.claimed: + admission.release() + + def forecast(self, req): + return self._run("forecast", req, TForecastResp) + + def inference(self, req): + return self._run("inference", req, TInferenceResp) + + def stop(self): + self.manager.stop() + + def begin_stop(self): + self.manager.begin_stop() + + def __getattr__(self, name): + return lambda *args, **kwargs: self.broker.call(name, args, kwargs) + + +class _ConnectionSlots: + def __init__(self, broker): + self.broker = broker + + def acquire(self, blocking=False): + return self.broker.connection(os.getpid(), True) + + def release(self): + return self.broker.connection(os.getpid(), False) + + +def _frontend_main(listener, address, authkey, stop_event, ready, config_snapshot): + os.environ["CUDA_VISIBLE_DEVICES"] = "" + os.environ["AINODE_FRONTEND_PROCESSES"] = "0" + if stop_event.is_set(): + return + torch.set_num_threads(1) + vars(AINodeDescriptor().get_config()).update(config_snapshot) + from iotdb.ainode.core.rpc.service import AINodeRPCService + + _BrokerManager.register("backend") + connection = _BrokerManager(address=address, authkey=authkey) + connection.connect() + broker = connection.backend() + service = AINodeRPCService(_FrontendHandler(broker)) + + def shutdown(): + stop_event.wait() + service.stop() + + threading.Thread(target=shutdown, daemon=True).start() + if torch.cuda.is_initialized(): + raise RuntimeError("Frontend initialized CUDA") + ready.set() + service.serve_inherited(listener, _ConnectionSlots(broker)) + if service.exit_code: + raise RuntimeError("Frontend RPC server failed") + + +class _StopSignal: + """A killed waiter cannot poison this lock-free, monotonic shared flag.""" + + def __init__(self, context): + self.flag = context.RawValue("b", False) + + def set(self): + self.flag.value = True + + def is_set(self): + return bool(self.flag.value) + + def wait(self, timeout=None): + deadline = None if timeout is None else time.monotonic() + timeout + while not self.is_set(): + if deadline is not None and time.monotonic() >= deadline: + return False + time.sleep(0.02) + return True + + +class ProcessFrontendServer: + def __init__(self, handler, count): + if not 1 <= count <= 8: + raise ValueError("AINODE_FRONTEND_PROCESSES must be 1..8") + self.handler = handler + self.count = count + self.context = mp.get_context("spawn") + self.stopped = _StopSignal(self.context) + self._lifecycle_lock = threading.Lock() + self.processes = [] + self.listener = None + self.server = None + self.directory = None + self.broker = BackendBroker(handler) + self.restart_times = [] + + def _spawn(self): + with self._lifecycle_lock: + if self.stopped.is_set(): + return + ready = _StopSignal(self.context) + process = self.context.Process( + target=_frontend_main, + args=( + self.listener, + self.address, + self.authkey, + self.stopped, + ready, + self.config_snapshot, + ), + name="ainode-frontend", + ) + process.start() + self.processes.append(process) + deadline = time.monotonic() + 60 + while not ready.is_set(): + if self.stopped.wait(0.05): + return + with self._lifecycle_lock: + if self.stopped.is_set(): + return + if not process.is_alive() or time.monotonic() >= deadline: + raise RuntimeError("Frontend did not become ready") + + def _start(self): + config = AINodeDescriptor().get_config() + self.directory = tempfile.TemporaryDirectory(prefix="ain-fp-") + self.address = os.path.join(self.directory.name, "broker") + self.authkey = os.urandom(32) + _BrokerManager.register( + "backend", + callable=lambda: self.broker, + exposed=("prepare", "abandon", "infer", "call", "connection"), + ) + manager = _BrokerManager(address=self.address, authkey=self.authkey) + self.server = manager.get_server() + self.config_snapshot = vars(config).copy() + family, kind, protocol, _, endpoint = socket.getaddrinfo( + config.get_ain_rpc_address(), + config.get_ain_rpc_port(), + type=socket.SOCK_STREAM, + flags=socket.AI_PASSIVE, + )[0] + self.listener = socket.socket(family, kind, protocol) + self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.listener.bind(endpoint) + self.listener.listen(256) + broker_thread = threading.Thread(target=self.server.serve_forever, daemon=True) + broker_thread.start() + while not hasattr(self.server, "stop_event") and broker_thread.is_alive(): + time.sleep(0.01) + + def serve(self): + try: + with self._lifecycle_lock: + if self.stopped.is_set(): + return + self._start() + for _ in range(self.count): + self._spawn() + while not self.stopped.wait(0.2): + with self._lifecycle_lock: + processes = self.processes.copy() + for process in processes: + with self._lifecycle_lock: + if self.stopped.is_set(): + return + if process.is_alive(): + continue + process.join() + self.processes.remove(process) + self.broker.reap(process.pid) + now = time.monotonic() + self.restart_times = [t for t in self.restart_times if now - t < 60] + if len(self.restart_times) >= 3: + self.handler.stop() + raise RuntimeError( + "Repeated frontend failure; refusing new work" + ) + self.restart_times.append(now) + logger.warning(f"Restarting failed CPU frontend {process.pid}") + self._spawn() + finally: + self.stop() + + def stop(self): + with self._lifecycle_lock: + if not self.stopped.is_set(): + begin_stop = getattr(self.handler, "begin_stop", None) + if begin_stop is not None: + begin_stop() + self.stopped.set() + if self.listener is not None: + self.listener.close() + self.listener = None + for process in self.processes.copy(): + process.join(timeout=10) + for signal in (process.terminate, process.kill): + if process.exitcode is not None: + break + try: + signal() + except OSError as error: + logger.error( + f"Could not signal CPU frontend {process.pid}: {error}" + ) + process.join(timeout=5) + if process.exitcode is None: + logger.error( + f"Could not confirm exit of CPU frontend {process.pid}" + ) + continue + self.broker.reap(process.pid) + self.processes.remove(process) + if self.server is not None: + if hasattr(self.server, "stop_event"): + self.server.stop_event.set() + self.server.listener.close() + self.server = None + if self.directory is not None: + self.directory.cleanup() + self.directory = None diff --git a/iotdb-core/ainode/iotdb/ainode/core/rpc/service.py b/iotdb-core/ainode/iotdb/ainode/core/rpc/service.py index 2420af201846d..40aa6f11a2f0d 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/rpc/service.py +++ b/iotdb-core/ainode/iotdb/ainode/core/rpc/service.py @@ -15,15 +15,17 @@ # specific language governing permissions and limitations # under the License. # +import os import socket import threading from thrift.protocol import TBinaryProtocol, TCompactProtocol from thrift.server import TServer -from thrift.transport import TSocket, TSSLSocket, TTransport +from thrift.transport import TSocket, TSSLSocket from iotdb.ainode.core.config import AINodeDescriptor from iotdb.ainode.core.log import Logger +from iotdb.ainode.core.rpc.framed_transport import BoundedFramedTransportFactory from iotdb.ainode.core.rpc.handler import AINodeRPCServiceHandler from iotdb.thrift.ainode import IAINodeRPCService @@ -32,34 +34,47 @@ class AINodeThreadPoolServer(TServer.TThreadedServer): def __init__(self, *args, **kwargs): + max_clients = kwargs.pop("max_clients", 256) + if max_clients < 1: + raise ValueError("max_clients must be positive") super().__init__(*args, **kwargs) + self._client_slots = threading.BoundedSemaphore(max_clients) + self._clients = set() + self._clients_lock = threading.Lock() self._stop_event = threading.Event() def serve(self) -> None: - self._stop_event.clear() logger.info("The RPC service thread pool of IoTDB-AINode begins to serve...") # Pump the socket for clients and spawn a dedicated thread per connection so # persistent pooled clients from DataNode/ConfigNode cannot starve concurrent RPCs. - self.serverTransport.listen() - handle = getattr(self.serverTransport, "handle", None) - if handle is not None and hasattr(handle, "settimeout"): - # set handle timeout to 100ms - handle.settimeout(0.1) + with self._clients_lock: + if self._stop_event.is_set(): + return + self.serverTransport.listen() + handle = getattr(self.serverTransport, "handle", None) + if handle is not None and hasattr(handle, "settimeout"): + # set handle timeout to 100ms + handle.settimeout(0.1) while not self._stop_event.is_set(): try: client = self.serverTransport.accept() if not client: continue - if self._stop_event.is_set(): - client.close() - break - t = threading.Thread( - target=self.handle, args=(client,), daemon=self.daemon - ) + with self._clients_lock: + if self._stop_event.is_set(): + client.close() + break + if not self._client_slots.acquire(blocking=False): + client.close() + logger.warning("AINode RPC connection limit reached") + continue + self._clients.add(client) try: - t.start() + threading.Thread( + target=self._serve_client, args=(client,), daemon=self.daemon + ).start() except Exception: - client.close() + self._release_client(client) raise except socket.timeout: continue @@ -71,11 +86,34 @@ def serve(self) -> None: "The RPC service thread pool of IoTDB-AINode has successfully stopped." ) + def _release_client(self, client): + try: + client.close() + finally: + with self._clients_lock: + self._clients.discard(client) + self._client_slots.release() + + def _serve_client(self, client): + try: + self.handle(client) + finally: + self._release_client(client) + def stop(self) -> None: - if not self._stop_event.is_set(): + with self._clients_lock: + if self._stop_event.is_set(): + return logger.info("Stopping the RPC service thread pool of IoTDB-AINode...") self._stop_event.set() self.serverTransport.close() + for client in self._clients: + handle = getattr(client, "handle", None) + if handle is not None: + try: + handle.shutdown(socket.SHUT_RDWR) + except OSError: + pass class AINodeRPCService(threading.Thread): @@ -84,6 +122,12 @@ def __init__(self, handler: AINodeRPCServiceHandler): self.exit_code = 0 self._stop_event = threading.Event() self._handler = handler + frontends = int(os.environ.get("AINODE_FRONTEND_PROCESSES", "0")) + if frontends: + from iotdb.ainode.core.rpc.process_frontend import ProcessFrontendServer + + self.__pool_server = ProcessFrontendServer(handler, frontends) + return processor = IAINodeRPCService.Processor(handler=self._handler) if AINodeDescriptor().get_config().get_ain_internal_ssl_enabled(): import ssl @@ -112,16 +156,36 @@ def __init__(self, handler: AINodeRPCServiceHandler): host=AINodeDescriptor().get_config().get_ain_rpc_address(), port=AINodeDescriptor().get_config().get_ain_rpc_port(), ) - transport_factory = TTransport.TFramedTransportFactory() + max_frame_size = AINodeDescriptor().get_config().get_ain_rpc_max_frame_size() + transport_factory = BoundedFramedTransportFactory(max_frame_size) + logger.info("AINode RPC receive frame limit: {} bytes".format(max_frame_size)) if AINodeDescriptor().get_config().get_ain_thrift_compression_enabled(): - protocol_factory = TCompactProtocol.TCompactProtocolFactory() + protocol_factory = TCompactProtocol.TCompactProtocolFactory( + string_length_limit=max_frame_size + ) else: - protocol_factory = TBinaryProtocol.TBinaryProtocolFactory() + protocol_factory = TBinaryProtocol.TBinaryProtocolFactory( + string_length_limit=max_frame_size + ) # Create daemon thread pool server self.__pool_server = AINodeThreadPoolServer( - processor, transport, transport_factory, protocol_factory, daemon=True + processor, + transport, + transport_factory, + protocol_factory, + daemon=True, + max_clients=AINodeDescriptor() + .get_config() + .get_ain_rpc_max_concurrent_client_num(), ) + def serve_inherited(self, listener, slots): + # Both plain and TLS transports retain their normal accept/protocol path. + self.__pool_server.serverTransport.handle = listener + self.__pool_server.serverTransport.listen = lambda: None + self.__pool_server._client_slots = slots + self.run() + def run(self) -> None: logger.info("The RPC service of IoTDB-AINode begins to run...") try: @@ -136,5 +200,6 @@ def stop(self) -> None: if not self._stop_event.is_set(): logger.info("Stopping the RPC service of IoTDB-AINode...") self._stop_event.set() + getattr(self._handler, "begin_stop", lambda: None)() self.__pool_server.stop() self._handler.stop() diff --git a/iotdb-core/ainode/iotdb/ainode/core/util/serde.py b/iotdb-core/ainode/iotdb/ainode/core/util/serde.py index f03d323f1b8ad..65be31cc360a1 100644 --- a/iotdb-core/ainode/iotdb/ainode/core/util/serde.py +++ b/iotdb-core/ainode/iotdb/ainode/core/util/serde.py @@ -15,6 +15,7 @@ # specific language governing permissions and limitations # under the License. # +import os import struct from enum import Enum @@ -60,32 +61,101 @@ def np_dtype(self): # Full data deserialized from iotdb tsblock is composed of [timestampList, multiple valueList, None, length]. # We only get valueList currently. def convert_tsblock_to_tensor(tsblock_data: bytes): - full_data = deserialize(tsblock_data) - # ensure the byteorder is correct. - for i, data in enumerate(full_data[1]): - if data.dtype.byteorder not in ("=", "|"): + _, columns, null_indicators, position_count = deserialize(tsblock_data) + values = [] + for index, data in enumerate(columns): + if not data.dtype.isnative: np_data = data.byteswap() - full_data[1][i] = np_data.view(np_data.dtype.newbyteorder()) + data = np_data.view(np_data.dtype.newbyteorder("=")) + nulls = None if null_indicators is None else null_indicators[index] + if nulls is not None and nulls.any() and data.dtype.kind in "biuf": + expanded = np.full( + position_count, np.nan, dtype=np.result_type(data, np.float32) + ) + expanded[~nulls] = data[~nulls] if len(data) == position_count else data + data = expanded + values.append(data) # the size should be [batch_size, target_count, sequence_length] - tensor_data = torch.from_numpy(np.stack(full_data[1], axis=0)).unsqueeze(0).float() + stacked = np.stack(values, axis=0) + if os.environ.get("AINODE_INPUT_CODEC") == "numpy" and stacked.dtype.kind in "biuf": + with np.errstate(over="ignore", invalid="ignore"): + values = stacked.astype(np.float32, copy=False) + return torch.from_numpy(values[None, ...]) + tensor_data = torch.from_numpy(stacked).unsqueeze(0).float() # data should be on CPU before passing to the inference request return tensor_data.to("cpu") # Convert DataFrame to TsBlock in binary, input shouldn't contain time column. # Maybe contain multiple value columns. -def convert_tensor_to_tsblock(data_tensor: torch.Tensor): - # Ensure the tensor is 2D with size [target_count, sequence_length] - if data_tensor.dim() == 0: - data_tensor = data_tensor.unsqueeze(0).unsqueeze(0) - elif data_tensor.dim() == 1: - data_tensor = data_tensor.unsqueeze(0) - - # Transpose the tensor to [sequence_length, target_count] - data_frame = pd.DataFrame(data_tensor.cpu()).T - # sequence_length, target_count - position_count, value_column_size = data_frame.shape[0], data_frame.shape[1] - +def convert_tensor_to_tsblock(data_tensor: torch.Tensor | np.ndarray): + if os.environ.get("AINODE_RESULT_CODEC", "numpy") == "numpy" and ( + ( + type(data_tensor) is torch.Tensor + and data_tensor.device.type == "cpu" + and data_tensor.layout == torch.strided + and not data_tensor.is_nested + and not data_tensor.requires_grad + and not data_tensor.is_neg() + and data_tensor.ndim == 2 + and data_tensor.numel() > 0 + and data_tensor.dtype + in ( + torch.bool, + torch.int32, + torch.int64, + torch.float32, + torch.float64, + ) + ) + or ( + type(data_tensor) is np.ndarray + and data_tensor.ndim == 2 + and data_tensor.size > 0 + and data_tensor.dtype.isnative + and data_tensor.dtype + in ( + np.bool_, + np.int32, + np.int64, + np.float32, + np.float64, + ) + ) + ): + array = np.asarray(data_tensor) + types = { + ("b", 1): (0, 0), + ("i", 4): (1, 1), + ("i", 8): (2, 2), + ("f", 4): (3, 1), + ("f", 8): (4, 2), + } + targets, length = array.shape + type_id, encoding = types[(array.dtype.kind, array.dtype.itemsize)] + parts = [ + targets.to_bytes(4, "big"), + bytes([type_id]) * targets, + length.to_bytes(4, "big"), + b"\x02" + bytes([encoding]) * targets, + b"\x00", + bytes(length * 8), + ] + dtype = array.dtype.newbyteorder(">") + for column in array: + values = ( + column.view(np.uint8) != 0 + if type_id == TSDataType.BOOLEAN.value + else column.astype(dtype, copy=False) + ) + parts.extend((b"\x00", values.tobytes())) + return b"".join(parts) + if isinstance(data_tensor, torch.Tensor): + if data_tensor.ndim < 2: + data_tensor = data_tensor.reshape(1, -1) + data_tensor = data_tensor.cpu() + data_frame = pd.DataFrame(data_tensor).T + position_count, value_column_size = data_frame.shape keys = data_frame.keys() binary = value_column_size.to_bytes(4, byteorder="big") diff --git a/iotdb-core/ainode/resources/conf/iotdb-ainode.properties b/iotdb-core/ainode/resources/conf/iotdb-ainode.properties index 6a8f02a62f74c..5bd506cf1cd8c 100644 --- a/iotdb-core/ainode/resources/conf/iotdb-ainode.properties +++ b/iotdb-core/ainode/resources/conf/iotdb-ainode.properties @@ -37,6 +37,16 @@ ain_rpc_address=127.0.0.1 # Datatype: String ain_rpc_port=10810 +# Maximum received RPC frame in bytes; account for all concurrent connections. +# DataNode's dn_thrift_max_frame_size independently limits received responses. +ain_rpc_max_frame_size=16384000 + +# Independent frame limit for responses from ConfigNode, in bytes. +ain_config_node_max_frame_size=16384000 + +# Deployment limit for a forecast's output length; the model must also support it. +ain_inference_max_output_length=2880 + # The DataNode address for fetching IoTDB data # Datatype: String ain_cluster_ingress_address=127.0.0.1 @@ -101,3 +111,18 @@ ain_inference_extra_memory_ratio=1.2 # It is recommended to use an absolute path. # Datatype: String # ain_thrift_ssl_key_file= + +# Maximum simultaneous RPC connections, including idle pooled connections. +# Connections above this limit are closed immediately instead of queued. +# Datatype: int (> 0) +ain_rpc_max_concurrent_client_num=256 + +# Greedy batch caps: requests and input time points across targets and inputs. +ain_inference_batch_max_requests=32 +ain_inference_batch_input_points=65536 + +# Bound physical work, including timed-out calls that are still executing. +ain_inference_max_inflight=256 +ain_inference_timeout_ms=60000 +# Kill an isolated worker that does not finish after its request deadline. +ain_inference_timeout_grace_ms=5000 diff --git a/iotdb-core/ainode/tests/test_builtin_model_limits.py b/iotdb-core/ainode/tests/test_builtin_model_limits.py index 3847acb8ddf75..ba9cd46a108c4 100644 --- a/iotdb-core/ainode/tests/test_builtin_model_limits.py +++ b/iotdb-core/ainode/tests/test_builtin_model_limits.py @@ -16,7 +16,9 @@ # under the License. # +import threading import unittest +from types import SimpleNamespace from unittest import mock import torch @@ -24,6 +26,8 @@ from iotdb.ainode.core.constant import TSStatusCode from iotdb.ainode.core.manager.inference_manager import InferenceManager from iotdb.ainode.core.model.model_info import BUILTIN_HF_TRANSFORMERS_MODEL_MAP +from iotdb.ainode.core.rpc.process_frontend import BackendBroker, _FrontendHandler +from iotdb.ainode.core.rpc.status import get_status from iotdb.ainode.core.util.serde import convert_tensor_to_tsblock from iotdb.thrift.ainode.ttypes import TForecastReq @@ -54,42 +58,63 @@ def test_loaded_model_rejects_invalid_horizon_and_serves_next_request(self): # With tirex2 loaded, a request outside its horizon must fail without reaching the # inference pool, and the next valid request must still be served by the pool. manager = self._manager(BUILTIN_HF_TRANSFORMERS_MODEL_MAP["tirex2"]) - manager._pool_controller = mock.Mock() - manager._pool_controller.has_running_pools.return_value = True + manager._accepting = True + manager._inflight_slots = threading.BoundedSemaphore(1) + manager._result_wrapper_lock = threading.RLock() + controller = mock.Mock() + controller.has_running_pools.return_value = True + manager._runtime = SimpleNamespace(controller=controller, pending={}) dispatched = [] - def process_request(request): + def complete_request(request, proxy): dispatched.append(request) - return [torch.zeros(1, request.output_length)] + manager._finish_request( + manager._runtime, + proxy.req_id, + [torch.zeros(1, request.output_length)], + ) - manager._process_request = process_request + controller.add_request.side_effect = complete_request + handler = mock.Mock(_inference_manager=manager) + handler._ensure_model_is_registered.return_value = get_status( + TSStatusCode.SUCCESS_STATUS + ) + broker = BackendBroker(handler) + frontend = _FrontendHandler(broker) input_data = convert_tensor_to_tsblock(torch.randn(1, 64)) - for output_length in (400, 0): - with self.subTest(output_length=output_length): - dispatched.clear() - rejected = manager.forecast( - TForecastReq( - modelId="tirex2", - inputData=input_data, - outputLength=output_length, + for path in (manager, frontend): + for output_length in (400, 0): + with self.subTest( + path=type(path).__name__, output_length=output_length + ): + dispatched.clear() + rejected = path.forecast( + TForecastReq( + modelId="tirex2", + inputData=input_data, + outputLength=output_length, + ) + ) + self.assertEqual( + rejected.status.code, TSStatusCode.AINODE_INTERNAL_ERROR.value ) - ) - self.assertEqual( - rejected.status.code, TSStatusCode.AINODE_INTERNAL_ERROR.value - ) - self.assertIn( - f"between 1 and 320, got {output_length}", rejected.status.message - ) - self.assertEqual(dispatched, []) + self.assertIn( + f"between 1 and 320, got {output_length}", + rejected.status.message, + ) + self.assertEqual(dispatched, []) - served = manager.forecast( - TForecastReq( - modelId="tirex2", inputData=input_data, outputLength=24 + served = path.forecast( + TForecastReq( + modelId="tirex2", inputData=input_data, outputLength=24 + ) + ) + self.assertEqual( + served.status.code, TSStatusCode.SUCCESS_STATUS.value ) - ) - self.assertEqual(served.status.code, TSStatusCode.SUCCESS_STATUS.value) - self.assertEqual([r.output_length for r in dispatched], [24]) + self.assertEqual([r.output_length for r in dispatched], [24]) + self.assertFalse(broker.admission.leases) if __name__ == "__main__": diff --git a/iotdb-core/ainode/tests/test_config.py b/iotdb-core/ainode/tests/test_config.py index 52955c511378f..447a234e1bf90 100644 --- a/iotdb-core/ainode/tests/test_config.py +++ b/iotdb-core/ainode/tests/test_config.py @@ -16,9 +16,12 @@ # under the License. # import sys +import tempfile import types import unittest from importlib import import_module +from pathlib import Path +from unittest.mock import patch class TEndPoint: @@ -67,5 +70,39 @@ def test_reject_malformed_endpoint(self): parse_endpoint_url(endpoint_url) +class ServingLimitsConfigTest(unittest.TestCase): + def test_invalid_serving_limits_abort_config_loading(self): + limits = ( + "ain_inference_max_inflight", + "ain_inference_timeout_ms", + "ain_inference_timeout_grace_ms", + "ain_inference_batch_max_requests", + "ain_inference_batch_input_points", + "ain_rpc_max_concurrent_client_num", + ) + later_properties = "ain_rpc_port=12345\nain_cluster_ingress_ssl_enabled=1\n" + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / config_module.AINODE_CONF_FILE_NAME + with patch.object(config_module, "AINODE_CONF_DIRECTORY_NAME", directory): + descriptor = config_module.AINodeDescriptor.__wrapped__ + for key in limits: + with self.subTest(key=key): + path.write_text( + f"{key}=0\n{later_properties}", encoding="utf-8" + ) + with self.assertRaisesRegex(ValueError, key): + descriptor() + path.write_text( + f"{limits[0]}=invalid\n{later_properties}", encoding="utf-8" + ) + with self.assertRaises(ValueError): + descriptor() + path.write_text(f"{limits[0]}=5\n{later_properties}", encoding="utf-8") + config = descriptor().get_config() + self.assertEqual(config.get_ain_inference_max_inflight(), 5) + self.assertEqual(config.get_ain_rpc_port(), 12345) + self.assertEqual(config.get_ain_cluster_ingress_ssl_enabled(), 1) + + if __name__ == "__main__": unittest.main() diff --git a/iotdb-core/ainode/tests/test_fp32_execution.py b/iotdb-core/ainode/tests/test_fp32_execution.py new file mode 100644 index 0000000000000..d71b81cb3ec6a --- /dev/null +++ b/iotdb-core/ainode/tests/test_fp32_execution.py @@ -0,0 +1,508 @@ +# 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 functools +import inspect +import os +import sys +import types +import unittest +from dataclasses import dataclass +from unittest.mock import patch + +import torch + +from iotdb.ainode.core.model.fp32_execution import ( + ExecutionOptions, + ModelStateMutation, + UnsupportedInput, + _fp32_enabled, + configure_fp32, + install_fp32_execution, +) + + +@dataclass +class Output: + prediction: torch.Tensor + extra: tuple = () + + +class Model(torch.nn.Module): + def __init__(self): + super().__init__() + self.weight = torch.nn.Parameter(torch.ones(())) + self.label = "preserved" + + def forward(self, value, scale=1, auxiliary=None): + if scale < 0: + raise ValueError("invalid scale") + result = value * self.weight * scale + if auxiliary is not None: + result = result + auxiliary + return Output(result, (result.clone(), None)) + + def generate(self, value): + return self(value, scale=2) + + +class BranchModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.weight = torch.nn.Parameter(torch.ones(())) + self.offset = 1 + + def forward(self, value): + scaled = value * self.weight + self.offset + if value.sum().item() < 0: + raise ValueError("negative input") + return scaled + + +class StatefulModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.calls = 0 + + def forward(self, value): + self.calls += 1 + return value + self.calls + + +def mutate_hidden_buffer(model): + model.running.add_(1) + + +class IndirectMutationModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.register_buffer("running", torch.zeros(())) + + def forward(self, value): + mutate_hidden_buffer(self) + return value + self.running + + +class EvalDropoutModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.dropout = torch.nn.Dropout(p=0.4) + + def forward(self, value): + return self.dropout(value * 2) + 1 + + +class FunctionalDropoutModel(torch.nn.Module): + def forward(self, value, training, probability=0.4): + return ( + torch.nn.functional.dropout(value * 2, p=probability, training=training) + 1 + ) + + +class FP32ExecutionTest(unittest.TestCase): + def test_preparation_audit_distinguishes_local_cell_and_external_closure(self): + class LocalCell(torch.nn.Module): + def forward(self, value): + local = 2 + + def read(): + return local + + return value * read() + + state = 0 + + class ClosureWrite(torch.nn.Module): + def forward(self, value): + nonlocal state + state += 1 + return value + + install_fp32_execution( + LocalCell().eval(), ExecutionOptions(compile=True) + )._check_preparation_code() + backend = install_fp32_execution( + ClosureWrite().eval(), ExecutionOptions(compile=True) + ) + with self.assertRaises(UnsupportedInput) as rejected: + backend._check_preparation_code() + message = str(rejected.exception) + for part in ("module=", "ClosureWrite.forward", __file__, "STORE_DEREF"): + self.assertIn(part, message) + + def test_preparation_audit_loaded_import_and_wrapped_forward(self): + import math + + class LoadedImport(torch.nn.Module): + def forward(self, value): + import math + + return value * math.pi + + def pi(self): + self.changed = True + + def decorate(function): + @functools.wraps(function) + def wrapper(self, value): + return function(self, value) + + return wrapper + + class WrappedWrite(torch.nn.Module): + @decorate + def forward(self, value): + self.changed = True + return value + + self.assertIsNotNone(math.pi) + install_fp32_execution( + LoadedImport().eval(), ExecutionOptions(compile=True) + )._check_preparation_code() + backend = install_fp32_execution( + WrappedWrite().eval(), ExecutionOptions(compile=True) + ) + with self.assertRaisesRegex( + UnsupportedInput, "WrappedWrite.forward.*STORE_ATTR" + ): + backend._check_preparation_code() + + def test_preparation_audit_rejects_unloaded_import(self): + class UnknownImport(torch.nn.Module): + def forward(self, value): + import ainode_unloaded_preparation_test_module + + return value + + backend = install_fp32_execution( + UnknownImport().eval(), ExecutionOptions(compile=True) + ) + with self.assertRaisesRegex( + UnsupportedInput, "UnknownImport.forward.*IMPORT_NAME" + ): + backend._check_preparation_code() + + def test_fp32_policy_enables_only_math_attention(self): + configure_fp32() + self.assertTrue(_fp32_enabled()) + self.assertTrue(torch.backends.cuda.math_sdp_enabled()) + self.assertFalse(torch.backends.cuda.flash_sdp_enabled()) + self.assertFalse(torch.backends.cuda.mem_efficient_sdp_enabled()) + self.assertFalse(torch.backends.cuda.cudnn_sdp_enabled()) + try: + torch.backends.cuda.enable_mem_efficient_sdp(True) + self.assertFalse(_fp32_enabled()) + finally: + configure_fp32() + + def test_default_compile_uses_strict_inductor_options(self): + model = Model().eval() + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + with patch("torch.compile", return_value=None) as compile_mock: + backend._compile() + compile_backend = compile_mock.call_args.kwargs["backend"] + graph = torch.fx.symbolic_trace(lambda value: value + 1) + value = torch.ones(2) + with patch("torch._inductor.compile", return_value=graph), patch( + "iotdb.ainode.core.model.fp32_execution._require_triton_ieee" + ): + compiled = compile_backend(graph, [value]) + self.assertTrue(torch.equal(compiled(value), value + 1)) + self.assertFalse(backend.inductor_options["triton.cudagraphs"]) + self.assertFalse(backend.inductor_options["use_fast_math"]) + self.assertFalse(backend.inductor_options["cuda.use_fast_math"]) + self.assertEqual(backend.inductor_options["compile_threads"], 1) + self.assertTrue(backend.inductor_options["force_disable_caches"]) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_triton_environment_and_effective_override_each_reject_optimization(self): + model = Model().eval().cuda() + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + value = torch.ones(2, device="cuda") + language = types.SimpleNamespace(fp32_default="tf32") + fake_triton = types.SimpleNamespace( + knobs=types.SimpleNamespace(language=language) + ) + with patch.dict(sys.modules, {"triton": fake_triton}), patch.dict( + os.environ, {"TRITON_F32_DEFAULT": "ieee"} + ), torch.no_grad(): + self.assertTrue( + torch.equal(backend.prepare_forward(value).prediction, value) + ) + language.fp32_default = "ieee" + os.environ["TRITON_F32_DEFAULT"] = "tf32" + self.assertTrue( + torch.equal(backend.prepare_forward(value).prediction, value) + ) + stats = backend.snapshot() + self.assertEqual(stats["counts"].get("compiled_objects", 0), 0) + self.assertEqual(stats["counts"].get("ineligible", 0), 2) + self.assertIn("Triton FP32 requires", str(stats["events"])) + + def test_cpu_fallback_keeps_model_attributes_generate_and_errors(self): + model = Model().eval() + signature = inspect.signature(model.forward) + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + value = torch.ones(2) + with torch.no_grad(): + self.assertTrue(torch.equal(model.generate(value).prediction, value * 2)) + with self.assertRaisesRegex(ValueError, "invalid scale"): + model(value, scale=-1) + self.assertEqual(model.label, "preserved") + self.assertEqual(inspect.signature(model.forward), signature) + self.assertEqual(backend.snapshot()["counts"]["ineligible"], 2) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_compile_requires_explicit_prepare_and_new_shapes_remain_eager(self): + model = Model().eval().cuda() + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + value = torch.ones(2, device="cuda") + with torch.no_grad(): + model(value, scale=2) + self.assertEqual(backend.snapshot()["counts"].get("compiled_objects", 0), 0) + with backend.prepare_calls(): + model.generate(value) + self.assertGreater( + backend.snapshot()["counts"].get("compile_success", 0), 0 + ) + self.assertTrue(torch.equal(model.generate(value).prediction, value * 2)) + self.assertEqual(backend.snapshot()["counts"]["compiled_calls"], 1) + model(torch.ones(3, device="cuda"), scale=2) + self.assertEqual(backend.snapshot()["counts"]["compiled_objects"], 1) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_eval_dropout_module_prepares_and_runs_compiled_segment(self): + model = EvalDropoutModel().eval().cuda() + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + value = torch.arange(32, dtype=torch.float32, device="cuda") + with torch.no_grad(): + backend.prepare_forward(value) + self.assertGreater( + backend.snapshot()["counts"].get("compile_success", 0), 0 + ) + result = model(value) + self.assertTrue(torch.equal(result, value * 2 + 1)) + self.assertGreater(backend.snapshot()["counts"].get("compiled_calls", 0), 0) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_functional_dropout_training_key_and_random_fallback(self): + model = FunctionalDropoutModel().eval().cuda() + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + random_model = FunctionalDropoutModel().eval().cuda() + random_backend = install_fp32_execution( + random_model, ExecutionOptions(compile=True) + ) + value = torch.ones(128, device="cuda") + with torch.no_grad(): + backend.prepare_forward(value, training=False) + self.assertGreater( + backend.snapshot()["counts"].get("compile_success", 0), 0 + ) + self.assertTrue(torch.equal(model(value, training=False), value * 2 + 1)) + before = backend.snapshot()["counts"].get("compiled_calls", 0) + state = torch.cuda.get_rng_state() + eager = backend.original_forward(value, training=True) + after_eager = torch.cuda.get_rng_state() + torch.cuda.set_rng_state(state) + actual = model(value, training=True) + self.assertTrue(torch.equal(actual, eager)) + self.assertTrue(torch.equal(torch.cuda.get_rng_state(), after_eager)) + self.assertEqual( + backend.snapshot()["counts"].get("compiled_calls", 0), before + ) + random_backend.prepare_forward(value, training=True) + self.assertTrue(torch.equal(torch.cuda.get_rng_state(), after_eager)) + self.assertGreater(backend.snapshot()["counts"].get("cache_miss", 0), 0) + random_stats = random_backend.snapshot() + self.assertEqual(random_stats["counts"]["compile_failure"], 1) + self.assertEqual(random_stats["prepared_entries"], 0) + self.assertIn("random compiled operation", str(random_stats["events"])) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_zero_probability_training_dropout_is_compiled(self): + model = FunctionalDropoutModel().eval().cuda() + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + value = torch.ones(32, device="cuda") + with torch.no_grad(): + backend.prepare_forward(value, training=True, probability=0.0) + self.assertGreater( + backend.snapshot()["counts"].get("compile_success", 0), 0 + ) + result = model(value, training=True, probability=0.0) + self.assertTrue(torch.equal(result, value * 2 + 1)) + self.assertGreater(backend.snapshot()["counts"].get("compiled_calls", 0), 0) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_single_signature_distinguishes_scalar_and_auxiliary_arguments(self): + model = Model().eval().cuda() + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + value = torch.ones(2, device="cuda") + auxiliary = torch.full_like(value, 3) + with torch.no_grad(), backend.prepare_calls(): + model(value, scale=2, auxiliary=auxiliary) + model(value, scale=1, auxiliary=auxiliary) + model(value, scale=2) + with torch.no_grad(): + result = model(value, scale=2, auxiliary=auxiliary) + self.assertTrue(torch.equal(result.prediction, value * 5)) + self.assertTrue(torch.equal(result.extra[0], value * 5)) + self.assertTrue( + torch.equal( + model(value, scale=1, auxiliary=auxiliary).prediction, value * 4 + ) + ) + self.assertTrue(torch.equal(model(value, scale=2).prediction, value * 2)) + stats = backend.snapshot() + self.assertEqual(stats["prepared_entries"], 1) + self.assertEqual(stats["counts"]["admission_full"], 2) + self.assertEqual(stats["counts"]["compiled_calls"], 1) + self.assertEqual(stats["counts"]["cache_miss"], 2) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_unknown_signature_skips_model_scan_and_preserves_forward_error(self): + model = Model().eval().cuda() + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + value = torch.ones(2, device="cuda") + with torch.no_grad(), patch.object( + model, "modules", side_effect=AssertionError("unexpected model scan") + ), patch.object( + model, "parameters", side_effect=AssertionError("unexpected parameter scan") + ), patch.object( + model, "buffers", side_effect=AssertionError("unexpected buffer scan") + ): + self.assertTrue(torch.equal(model(value).prediction, value)) + with self.assertRaisesRegex(ValueError, "invalid scale"): + model(value, scale=-1) + stats = backend.snapshot() + self.assertEqual(stats["counts"]["online_calls"], 2) + self.assertEqual(stats["counts"]["cache_miss"], 2) + self.assertIn("torch.float32", stats["input_dtype_counts"]) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_prepared_signature_still_checks_model_training_state(self): + model = Model().eval().cuda() + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + value = torch.ones(2, device="cuda") + with torch.no_grad(): + backend.prepare_forward(value) + self.assertEqual(backend.snapshot()["prepared_entries"], 1) + model.train() + self.assertTrue(torch.equal(model(value).prediction, value)) + stats = backend.snapshot()["counts"] + self.assertEqual(stats["ineligible"], 1) + self.assertEqual(stats.get("cache_hit", 0), 0) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_lazy_compiler_failure_and_real_business_error(self): + model = Model().eval().cuda() + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + value = torch.ones(2, device="cuda") + + def failing_compile(*args, **kwargs): + def run(*args, **kwargs): + raise torch._dynamo.exc.Unsupported("lazy compiler failure") + + return run + + with patch( + "torch.compile", side_effect=failing_compile + ) as compile_mock, torch.no_grad(): + with self.assertRaisesRegex(ValueError, "invalid scale"): + backend.prepare_forward(value, scale=-1) + backend.prepare_forward(value) + backend.prepare_forward(value, scale=2) + self.assertTrue(torch.equal(model(value).prediction, value)) + compile_mock.assert_called_once() + stats = backend.snapshot() + self.assertEqual(stats["blacklisted_entries"], 1) + self.assertEqual(stats["prepared_entries"], 0) + self.assertEqual(stats["counts"]["admission_full"], 1) + self.assertEqual(stats["counts"]["compile_failure"], 1) + self.assertIn("lazy compiler failure", str(stats["events"])) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_partial_compile_guard_miss_does_not_compile_and_business_error_survives( + self, + ): + model = BranchModel().eval().cuda() + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + value = torch.ones(2, device="cuda") + with torch.no_grad(): + backend.prepare_forward(value) + self.assertGreater( + backend.snapshot()["counts"].get("compile_success", 0), 0 + ) + before = backend.snapshot()["counts"]["compiler_graphs"] + model.offset = 2 + self.assertTrue(torch.equal(model(value), value + 2)) + with self.assertRaisesRegex(ValueError, "negative input"): + model(-value) + self.assertEqual(backend.snapshot()["counts"]["compiler_graphs"], before) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_stateful_forward_runs_only_once_on_rejected_preparation(self): + model = StatefulModel().eval().cuda() + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + value = torch.ones(2, device="cuda") + with torch.no_grad(): + result = backend.prepare_forward(value) + self.assertEqual(model.calls, 1) + self.assertTrue(torch.equal(result, value + 1)) + self.assertEqual(backend.snapshot()["counts"]["admission_rejected"], 1) + self.assertEqual(backend.snapshot()["counts"].get("compiled_objects", 0), 0) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_indirect_buffer_mutation_is_restored_and_aborts_before_retry(self): + model = IndirectMutationModel().eval().cuda() + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + value = torch.ones(2, device="cuda") + with torch.no_grad(), self.assertRaisesRegex(ModelStateMutation, "running"): + backend.prepare_forward(value) + self.assertEqual(model.running.item(), 0) + self.assertEqual(backend.snapshot()["counts"]["state_mutation"], 1) + self.assertEqual(backend.snapshot()["counts"].get("compiled_objects", 0), 0) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_preparation_rejects_hooks_before_extra_forward(self): + model = Model().eval().cuda() + observed = [] + handle = model.register_forward_hook(lambda *args: observed.append(1)) + backend = install_fp32_execution(model, ExecutionOptions(compile=True)) + try: + with torch.no_grad(), backend.prepare_calls(): + model(torch.ones(2, device="cuda")) + finally: + handle.remove() + self.assertEqual(observed, [1]) + self.assertEqual(backend.snapshot()["counts"]["admission_rejected"], 1) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_backup_limit_rejects_probe_and_keeps_original_behavior(self): + model = Model().eval().cuda() + backend = install_fp32_execution( + model, ExecutionOptions(compile=True, max_state_backup_bytes=1) + ) + value = torch.ones(2, device="cuda") + with torch.no_grad(): + result = backend.prepare_forward(value) + self.assertTrue(torch.equal(result.prediction, value)) + self.assertEqual(backend.snapshot()["counts"]["admission_rejected"], 1) + self.assertIn("backup byte limit", str(backend.snapshot()["events"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_inference_inputs.py b/iotdb-core/ainode/tests/test_inference_inputs.py new file mode 100644 index 0000000000000..e7b677ba18527 --- /dev/null +++ b/iotdb-core/ainode/tests/test_inference_inputs.py @@ -0,0 +1,454 @@ +# 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 +import threading +import unittest +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import torch + +from iotdb.ainode.core.config import AINodeDescriptor +from iotdb.ainode.core.constant import TSStatusCode +from iotdb.ainode.core.inference.batcher.basic_batcher import BasicBatcher +from iotdb.ainode.core.inference.inference_request import ( + InferenceRequest, + InferenceRequestProxy, +) +from iotdb.ainode.core.inference.inference_request_pool import InferenceRequestPool +from iotdb.ainode.core.inference.pipeline.basic_pipeline import ( + ChatPipeline, + ClassificationPipeline, + ForecastPipeline, +) +from iotdb.ainode.core.manager.inference_manager import InferenceManager +from iotdb.ainode.core.model.chronos2.dataset import Chronos2Dataset +from iotdb.ainode.core.model.chronos2.pipeline_chronos2 import Chronos2Pipeline +from iotdb.ainode.core.model.sundial.pipeline_sundial import SundialPipeline +from iotdb.ainode.core.model.timer_xl.pipeline_timer import TimerPipeline +from iotdb.ainode.core.model.toto.pipeline_toto import TotoPipeline +from iotdb.ainode.core.util.serde import convert_tensor_to_tsblock +from iotdb.thrift.ainode.ttypes import TForecastReq, TInferenceReq + + +class RecordingPipeline(ForecastPipeline): + def __init__(self): + self.calls = [] + + def forecast(self, inputs, **kwargs): + self.calls.append((inputs, kwargs)) + return [ + item["targets"][:, -1:].expand(-1, kwargs["output_length"]) + for item in inputs + ] + + +class RecordingOptions: + def __init__(self): + self.calls = [] + + def preprocess(self, inputs, **options): + self.calls.append(("preprocess", options)) + return inputs + + def run(self, inputs, **options): + self.calls.append(("run", options)) + return [ + item["targets"][:, -1:].expand(-1, options["output_length"]) + for item in inputs + ] + + def postprocess(self, outputs, **options): + self.calls.append(("postprocess", options)) + return [output + float(options["offset"]) for output in outputs] + + +class RecordingForecastOptions(RecordingOptions, ForecastPipeline): + forecast = RecordingOptions.run + + +class RecordingClassificationOptions(RecordingOptions, ClassificationPipeline): + classify = RecordingOptions.run + + +class RecordingChatOptions(RecordingOptions, ChatPipeline): + chat = RecordingOptions.run + + +class InferenceInputsTest(unittest.TestCase): + def pool(self, requests): + pool = InferenceRequestPool.__new__(InferenceRequestPool) + pool.device = torch.device("cpu") + pool.pool_id = 0 + pool._backend = SimpleNamespace( + move_tensor=lambda tensor, device: tensor.to(device) + ) + pool._batcher = BasicBatcher() + pool._request_scheduler = SimpleNamespace(schedule_step=lambda: requests) + pool._finished_queue = queue.Queue() + pool._waiting_queue = queue.Queue() + pool._logger = MagicMock() + pool._inference_pipeline = RecordingPipeline() + return pool + + def run_pipeline(self, pipeline, loaded, req): + manager = InferenceManager.__new__(InferenceManager) + manager._accepting = True + manager._inflight_slots = threading.BoundedSemaphore(1) + manager._cpu_slot = threading.BoundedSemaphore(1) + manager._result_wrapper_lock = threading.RLock() + manager._backend = SimpleNamespace(torch_device=torch.device) + manager._model_manager = MagicMock() + manager._model_manager.get_model_info.return_value.max_output_length = None + controller = MagicMock() + manager._runtime = SimpleNamespace(controller=controller, pending={}) + controller.has_running_pools.return_value = loaded + controller.requires_loaded_pool.return_value = False + + def dispatch(request, proxy): + pool = self.pool([request]) + pool._inference_pipeline = pipeline + pool._step() + result = pool._finished_queue.get_nowait() + manager._finish_request( + manager._runtime, + result.req_id, + output=result.get_final_output() if result.error is None else None, + error=result.error, + ) + + controller.add_request.side_effect = dispatch + with patch( + "iotdb.ainode.core.manager.inference_manager.load_pipeline", + return_value=pipeline, + ): + if isinstance(req, TForecastReq): + return manager.forecast(req) + return manager.inference(req) + + def test_invalid_output_length_is_rejected_before_inference(self): + dataset = convert_tensor_to_tsblock(torch.ones(1, 4)) + max_output_length = 4 + with ( + patch.object( + AINodeDescriptor().get_config(), + "get_ain_inference_max_output_length", + return_value=max_output_length, + ), + patch.object(InferenceManager, "_execute_prepared") as execute_prepared, + ): + for output_length in (0, -1, max_output_length + 1): + with self.subTest(output_length=output_length): + req = TForecastReq( + modelId="custom", + inputData=dataset, + outputLength=output_length, + ) + response = self.run_pipeline(MagicMock(), True, req) + self.assertEqual( + response.status.code, + TSStatusCode.AINODE_INTERNAL_ERROR.get_status_code(), + ) + self.assertEqual( + response.status.message, + f"Attribute output_length expect value between 1 and " + f"{max_output_length}, got {output_length} instead.", + ) + execute_prepared.assert_not_called() + + def test_cpu_and_pool_forward_options_to_all_pipeline_stages(self): + dataset = convert_tensor_to_tsblock(torch.ones(1, 4)) + for pipeline_type in ( + RecordingForecastOptions, + RecordingClassificationOptions, + RecordingChatOptions, + ): + for offset in ("2", "5"): + expected_options = { + "output_length": 2, + "predict_batches_jointly": False, + "revin": "false", + "batch_size": "3", + "num_samples": "4", + "offset": offset, + } + req = TInferenceReq( + modelId="custom", + dataset=dataset, + inferenceAttributes={ + "outputLength": "2", + "_ain_timeout_ms": "10000", + "predict_batches_jointly": "false", + "revin": "false", + "batch_size": "3", + "num_samples": "4", + "offset": offset, + }, + ) + expected = convert_tensor_to_tsblock( + torch.full((1, 2), 1 + float(offset), dtype=torch.float64) + ) + for loaded in (False, True): + with self.subTest( + pipeline=pipeline_type.__name__, offset=offset, loaded=loaded + ): + pipeline = pipeline_type() + response = self.run_pipeline(pipeline, loaded, req) + self.assertEqual( + response.status.code, 200, response.status.message + ) + self.assertEqual(response.inferenceResult, [expected]) + self.assertEqual( + pipeline.calls, + [ + (stage, expected_options) + for stage in ("preprocess", "run", "postprocess") + ], + ) + + def test_builtin_revin_is_a_strict_boolean_in_cpu_and_pool(self): + dataset = convert_tensor_to_tsblock(torch.ones(1, 4)) + for model_id, pipeline_type, shape in ( + ("timer_xl", TimerPipeline, (1, 2)), + ("sundial", SundialPipeline, (1, 10, 2)), + ): + for loaded in (False, True): + for value, expected in (("FaLsE", False), ("true", True), ("0", None)): + with self.subTest(model=model_id, loaded=loaded, revin=value): + pipeline = pipeline_type.__new__(pipeline_type) + pipeline.model_info = SimpleNamespace(model_id=model_id) + generate = MagicMock(return_value=torch.ones(shape)) + pipeline.model = SimpleNamespace(generate=generate) + req = TForecastReq( + modelId=model_id, + inputData=dataset, + outputLength=2, + options={"revin": value}, + ) + response = self.run_pipeline(pipeline, loaded, req) + if expected is None: + self.assertNotEqual(response.status.code, 200) + self.assertIn( + "revin must be true or false", response.status.message + ) + generate.assert_not_called() + else: + self.assertEqual( + response.status.code, 200, response.status.message + ) + generate.assert_called_once() + self.assertIs(generate.call_args.kwargs["revin"], expected) + + def test_chronos2_integer_wire_options_in_cpu_and_pool(self): + dataset = convert_tensor_to_tsblock(torch.ones(1, 4)) + for loaded in (False, True): + with self.subTest(loaded=loaded): + pipeline = Chronos2Pipeline.__new__(Chronos2Pipeline) + pipeline.model_info = SimpleNamespace(model_id="chronos2") + pipeline.model = SimpleNamespace( + chronos_config=SimpleNamespace( + context_length=256, + output_patch_size=2, + max_output_patches=4, + quantiles=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], + ) + ) + pipeline._predict_batch = MagicMock(return_value=[torch.ones(1, 9, 2)]) + req = TForecastReq( + modelId="chronos2", + inputData=dataset, + outputLength=2, + options={ + "context_length": "2", + "batch_size": "3", + "max_output_patches": "1", + "output_patch_size": "ignored", + }, + ) + with patch.object( + Chronos2Dataset, + "convert_inputs", + wraps=Chronos2Dataset.convert_inputs, + ) as convert: + response = self.run_pipeline(pipeline, loaded, req) + self.assertEqual(response.status.code, 200, response.status.message) + self.assertEqual(convert.call_args.kwargs["context_length"], 2) + self.assertEqual(convert.call_args.kwargs["batch_size"], 3) + self.assertEqual(convert.call_args.kwargs["output_patch_size"], 2) + self.assertEqual( + pipeline._predict_batch.call_args.kwargs["max_output_patches"], 1 + ) + + pipeline._predict_batch.reset_mock() + for key, value in ( + ("context_length", "2.5"), + ("batch_size", "0"), + ("max_output_patches", "-1"), + ): + with self.subTest(option=key): + req.options = {key: value} + response = self.run_pipeline(pipeline, loaded, req) + self.assertNotEqual(response.status.code, 200) + self.assertIn( + f"{key} must be a positive integer", response.status.message + ) + pipeline._predict_batch.assert_not_called() + + def test_sampling_integer_wire_options_in_cpu_and_pool(self): + dataset = convert_tensor_to_tsblock(torch.ones(1, 4)) + for model_id, pipeline_type in ( + ("sundial", SundialPipeline), + ("toto", TotoPipeline), + ): + for loaded in (False, True): + with self.subTest(model=model_id, loaded=loaded): + pipeline = pipeline_type.__new__(pipeline_type) + pipeline.model_info = SimpleNamespace(model_id=model_id) + options = {"num_samples": "2"} + if model_id == "sundial": + compute = MagicMock(return_value=torch.ones(1, 2, 2)) + pipeline.model = SimpleNamespace(generate=compute) + else: + compute = MagicMock( + return_value=SimpleNamespace(mean=torch.ones(1, 2)) + ) + pipeline.model = SimpleNamespace(device=torch.device("cpu")) + pipeline._forecaster = SimpleNamespace(forecast=compute) + options["samples_per_batch"] = "1" + req = TForecastReq( + modelId=model_id, + inputData=dataset, + outputLength=2, + options=options, + ) + response = self.run_pipeline(pipeline, loaded, req) + self.assertEqual(response.status.code, 200, response.status.message) + compute.assert_called_once() + for key, value in options.items(): + self.assertEqual(compute.call_args.kwargs[key], int(value)) + + compute.reset_mock() + for key in options: + with self.subTest(option=key): + req.options = {**options, key: "0"} + response = self.run_pipeline(pipeline, loaded, req) + self.assertNotEqual(response.status.code, 200) + self.assertIn( + f"{key} must be a positive integer", + response.status.message, + ) + compute.assert_not_called() + + def test_pool_preserves_multiple_targets_and_options(self): + targets = torch.arange(8.0).reshape(2, 4) + request = InferenceRequest( + "r1", + "chronos2", + model_inputs=[{"targets": targets}], + output_length=2, + inference_attrs={"batch_size": 3}, + ) + pool = self.pool([request]) + pool._step() + result = pool._finished_queue.get_nowait() + self.assertIsNone(result.error) + torch.testing.assert_close( + result.get_final_output(), torch.tensor([[[3.0, 3.0], [7.0, 7.0]]]) + ) + actual_inputs, actual_options = pool._inference_pipeline.calls[0] + torch.testing.assert_close(actual_inputs[0]["targets"], targets) + self.assertEqual(actual_options["batch_size"], 3) + + def test_different_options_are_not_batched_together(self): + requests = [ + InferenceRequest( + str(i), + "sundial", + inputs=torch.ones(1, 1, 4), + output_length=2, + inference_attrs={"num_samples": i + 1}, + ) + for i in range(2) + ] + pool = self.pool(requests) + pool._step() + self.assertEqual(len(pool._inference_pipeline.calls), 2) + self.assertEqual(pool._finished_queue.qsize(), 2) + + def test_matching_plain_requests_still_batch(self): + requests = [ + InferenceRequest( + str(i), "sundial", inputs=torch.ones(1, 1, 4), output_length=2 + ) + for i in range(2) + ] + pool = self.pool(requests) + pool._step() + self.assertEqual(len(pool._inference_pipeline.calls), 1) + self.assertEqual(len(pool._inference_pipeline.calls[0][0]), 2) + + def test_host_staged_pipeline_keeps_all_inputs_on_cpu(self): + request = InferenceRequest( + "r", + "chronos2", + output_length=2, + model_inputs=[{"targets": torch.ones(2, 4)}], + ) + pool = self.pool([request]) + pool.device = torch.device("cuda") + pool._inference_pipeline.input_device = torch.device("cpu") + pool._backend.move_tensor = MagicMock(side_effect=lambda tensor, device: tensor) + pool._build_batch_input_list([request]) + pool._backend.move_tensor.assert_called_once() + self.assertEqual( + pool._backend.move_tensor.call_args.args[1], torch.device("cpu") + ) + + def test_invalid_request_is_reported_without_stopping_worker(self): + bad = InferenceRequest( + "bad", + "chronos2", + output_length=2, + model_inputs=[{"targets": torch.full((1, 4), float("inf"))}], + ) + pool = self.pool([bad]) + pool._step() + result = pool._finished_queue.get_nowait() + self.assertIn("infinite values", result.error) + good = InferenceRequest( + "good", "chronos2", inputs=torch.ones(1, 1, 4), output_length=2 + ) + pool._request_scheduler = SimpleNamespace(schedule_step=lambda: [good]) + pool._step() + self.assertIsNone(pool._finished_queue.get_nowait().error) + + def test_proxy_result_can_arrive_before_wait(self): + proxy = InferenceRequestProxy("r") + proxy.set_result("ready") + self.assertEqual(proxy.wait_for_result(), "ready") + + def test_proxy_propagates_worker_error(self): + proxy = InferenceRequestProxy("r") + proxy.set_exception(ValueError("invalid input")) + with self.assertRaisesRegex(ValueError, "invalid input"): + proxy.wait_for_result() + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_inference_recovery.py b/iotdb-core/ainode/tests/test_inference_recovery.py new file mode 100644 index 0000000000000..652d86760f889 --- /dev/null +++ b/iotdb-core/ainode/tests/test_inference_recovery.py @@ -0,0 +1,358 @@ +# 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 os +import queue +import signal +import struct +import subprocess +import sys +import threading +import time +import unittest +from collections import deque +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import numpy as np +import torch + +from iotdb.ainode.core.inference import pool_controller +from iotdb.ainode.core.inference.inference_request import ( + InferenceRequest, + InferenceResult, +) +from iotdb.ainode.core.inference.inference_request_pool import InferenceRequestPool +from iotdb.ainode.core.manager import inference_manager, utils +from iotdb.ainode.core.rpc.process_frontend import BackendBroker, LeaseRegistry +from iotdb.thrift.common.ttypes import TSStatus + +WORKER_STARTUP_TIMEOUT = 45 + + +class RecoveryWorker(InferenceRequestPool): + def run(self): + self._waiting_queue._writer.close() + self._finished_queue._reader.close() + if self.model_info.model_id == "chronos2" and self.device.index == 1: + self._finished_queue.put((self.pool_id, "Fixture model load failed")) + return + self._finished_queue.put((self.pool_id, None)) + while not self._stop_event.is_set(): + try: + request = self._waiting_queue.get(timeout=0.1) + except queue.Empty: + continue + offset = request.inference_attrs.get("offset", 0) + if offset == "half-frame": + self._finished_queue._wlock.acquire() + os.write( + self._finished_queue._writer.fileno(), + struct.pack("!i", 4096) + b"x", + ) + while True: + time.sleep(1) + if offset == "request-error": + self._finished_queue.put( + InferenceResult(request.req_id, error="Invalid model option") + ) + continue + values = np.full( + (1, 1, request.output_length), int(offset), dtype=np.float32 + ) + self._finished_queue.put(InferenceResult(request.req_id, values)) + + +class InferenceRecoveryTest(unittest.TestCase): + def _run_bounded_fixture(self, case): + with subprocess.Popen( + [sys.executable, str(Path(__file__).resolve()), case], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) as process: + try: + output, _ = process.communicate(timeout=180) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + output, _ = process.communicate() + self.fail(f"Recovery fixture hung:\n{output.decode(errors='replace')}") + self.assertEqual(process.returncode, 0, output.decode(errors="replace")) + + def test_partial_frame_and_old_lease_do_not_reach_new_pool(self): + self._run_bounded_fixture("half-frame") + + def test_idle_exit_and_stop_during_backoff(self): + self._run_bounded_fixture("idle") + + def test_unconfirmed_teardown_keeps_pending_and_blocks_replacement(self): + manager = inference_manager.InferenceManager.__new__( + inference_manager.InferenceManager + ) + manager._new_runtime = MagicMock() + controller = MagicMock() + controller.desired_residency.return_value = (set(), set()) + controller.stop.side_effect = RuntimeError( + "Could not confirm all model workers exited" + ) + release = MagicMock() + proxy = MagicMock() + runtime = SimpleNamespace( + retired=False, + fault="lost worker", + controller=controller, + pending={"old": (None, proxy, release)}, + ) + with self.assertRaisesRegex(RuntimeError, "Could not confirm"): + manager._recover(runtime) + self.assertIn("old", runtime.pending) + manager._new_runtime.assert_not_called() + release.assert_not_called() + proxy.set_exception.assert_not_called() + + def test_failed_candidates_are_retired_within_the_retry_budget(self): + manager = inference_manager.InferenceManager.__new__( + inference_manager.InferenceManager + ) + manager._stopping = threading.Event() + manager._result_wrapper_lock = threading.RLock() + manager._restart_times = deque() + manager._RECOVERY_DELAYS = (0, 0, 0) + manager._accepting = False + old = MagicMock() + old.controller.desired_residency.return_value = (set(), set()) + candidates = [MagicMock() for _ in range(3)] + for candidate in candidates: + candidate.controller.restore_residency.side_effect = RuntimeError( + "load failed" + ) + manager._new_runtime = MagicMock(side_effect=candidates) + manager._retire_runtime = MagicMock() + with self.assertRaisesRegex(RuntimeError, "budget exhausted"): + manager._recover(old) + self.assertEqual(manager._new_runtime.call_count, 3) + self.assertEqual( + [call.args[0] for call in manager._retire_runtime.call_args_list], + [old, *candidates], + ) + self.assertFalse(manager._accepting) + self.assertIsNone(manager._candidate) + + +class RecoveryFixture(unittest.TestCase): + def wait_until(self, condition, seconds=14): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if condition(): + return + time.sleep(0.02) + self.fail("Recovery condition did not become true") + + def request(self, model="chronos2", offset=4, timeout=8): + return InferenceRequest( + "reused-id", + model, + inputs=torch.ones(1, 1, 4), + output_length=2, + inference_attrs={"offset": offset}, + _deadline=time.monotonic() + timeout, + ) + + def setUp(self): + fake_models = SimpleNamespace( + is_model_registered=lambda _: True, + get_model_info=lambda model_id: SimpleNamespace( + model_id=model_id, max_output_length=None + ), + ) + patches = ( + patch.object(inference_manager, "ModelManager", return_value=fake_models), + patch.object(pool_controller, "ModelManager", return_value=fake_models), + patch.object(pool_controller, "InferenceRequestPool", RecoveryWorker), + patch.object( + utils, + "evaluate_system_resources", + return_value={"total_mem": 2**45, "free_mem": 2**45}, + ), + patch.object( + inference_manager.InferenceManager, "_RECOVERY_DELAYS", (0.5, 1, 2) + ), + patch.object( + inference_manager.InferenceManager, + "_START_TIMEOUT", + WORKER_STARTUP_TIMEOUT, + ), + patch.dict( + os.environ, AINODE_REQUEST_IPC="numpy", AINODE_FRONTEND_PROCESSES="0" + ), + ) + for patcher in patches: + patcher.start() + self.addCleanup(patcher.stop) + self.manager = inference_manager.InferenceManager() + self.addCleanup(self.manager.stop) + self.device = torch.device("cpu") + self.broker = BackendBroker( + SimpleNamespace( + _inference_manager=self.manager, + _ensure_model_is_registered=lambda _: TSStatus(code=200), + ) + ) + self.broker.admission = LeaseRegistry(3) + + def load(self, *models): + for index, model in enumerate(models): + device = self.device if index == 0 else torch.device("cpu", index) + self.assertEqual(self.manager.load_model(model, [device]).code, 200) + self.wait_until( + lambda: all( + self.manager._runtime.controller.has_running_pools(model) + for model in models + ), + seconds=WORKER_STARTUP_TIMEOUT, + ) + + def prepare(self, key, model="chronos2"): + status, admitted, _ = self.broker.prepare(model, key, owner=11) + self.assertEqual(status.code, 200, status.message) + self.assertTrue(admitted) + + def assert_exited(self, *pids): + for pid in pids: + with self.assertRaises(ProcessLookupError): + os.kill(pid, 0) + + def scenario_half_frame(self): + old = self.manager._runtime + failed_device = torch.device("cpu", 1) + self.assertEqual( + self.manager.load_model("chronos2", [self.device, failed_device]).code, 200 + ) + self.wait_until( + lambda: not old.controller._transition_counts["chronos2"], + seconds=WORKER_STARTUP_TIMEOUT, + ) + self.assertEqual( + old.controller.desired_residency()[0], {("chronos2", self.device)} + ) + self.assertTrue(old.controller.has_running_pools("chronos2")) + self.assertFalse(old.controller.has_pool_on_device(failed_device)) + self.assertEqual(self.manager.load_model("sundial", [failed_device]).code, 200) + self.wait_until( + lambda: old.controller.has_running_pools("sundial"), + seconds=WORKER_STARTUP_TIMEOUT, + ) + self.assertEqual( + old.controller.desired_residency()[0], + {("chronos2", self.device), ("sundial", failed_device)}, + ) + self.assertEqual(self.manager.unload_model("timer_xl", [self.device]).code, 200) + workers = old.controller.pool_snapshot() + victim = old.controller.get_request_pool( + "chronos2", + self.device, + old.controller.get_pool_ids("chronos2", self.device)[0], + ) + old_pids = [worker.pid for worker, _, _ in workers.values()] + victim_pid = victim.pid + + frame_read = threading.Event() + original_recv = old.queue._reader._recv + + def observe_frame(size): + if size == 4096: + frame_read.set() + return original_recv(size) + + old.queue._reader._recv = observe_frame + self.prepare("old-preparation") + self.prepare("partial") + with ThreadPoolExecutor(max_workers=1) as executor: + request = self.request(offset="half-frame", timeout=3) + inference = executor.submit(self.broker.infer, "partial", request) + self.assertTrue(frame_read.wait(2), "reader did not enter a partial frame") + with self.assertRaises(TimeoutError): + inference.result(timeout=4) + self.assertFalse(self.broker.abandon("partial")) + os.kill(victim_pid, signal.SIGKILL) + self.wait_until(lambda: not self.manager._accepting) + self.assertNotEqual( + self.manager.load_model("timer_xl", [self.device]).code, 200 + ) + self.wait_until( + lambda: self.manager._accepting and self.manager._runtime is not old, + seconds=WORKER_STARTUP_TIMEOUT, + ) + new = self.manager._runtime + self.assertIsNot(new.queue, old.queue) + self.assertFalse(old.receiver.is_alive()) + self.assert_exited(*old_pids) + self.assertNotIn("partial", self.broker.admission.leases) + self.assertTrue(new.controller.has_running_pools("chronos2")) + self.assertTrue(new.controller.has_running_pools("sundial")) + self.assertFalse(new.controller.requires_loaded_pool("timer_xl")) + self.assertFalse(new.controller.has_running_pools("timer_xl")) + with self.assertRaisesRegex(RuntimeError, "workers changed"): + self.broker.infer("old-preparation", self.request()) + self.assertFalse(self.broker.abandon("old-preparation")) + self.prepare("new") + np.testing.assert_array_equal( + self.broker.infer("new", self.request(offset=7)), np.full((1, 1, 2), 7) + ) + self.assertFalse(self.broker.admission.leases) + + def scenario_idle(self): + self.load("chronos2") + old = self.manager._runtime + victim, _, _ = next(iter(old.controller.pool_snapshot().values())) + pid = victim.pid + os.kill(pid, signal.SIGKILL) + self.wait_until( + lambda: self.manager._accepting and self.manager._runtime is not old, + seconds=WORKER_STARTUP_TIMEOUT, + ) + self.assert_exited(pid) + current = self.manager._runtime + self.prepare("ordinary-error") + with self.assertRaisesRegex(Exception, "Invalid model option"): + self.broker.infer("ordinary-error", self.request(offset="request-error")) + self.assertIs(self.manager._runtime, current) + self.assertTrue(self.manager._accepting) + self.prepare("after-idle-fault") + np.testing.assert_array_equal( + self.broker.infer("after-idle-fault", self.request()), np.full((1, 1, 2), 4) + ) + victim, _, _ = next(iter(current.controller.pool_snapshot().values())) + pid = victim.pid + with patch.object(self.manager, "_RECOVERY_DELAYS", (10, 10, 10)): + os.kill(pid, signal.SIGKILL) + self.wait_until(lambda: current.retired) + self.manager.stop() + self.manager.stop() + self.assert_exited(pid) + self.assertFalse(self.manager._accepting) + self.assertFalse(self.manager._watchdog_thread.is_alive()) + self.assertIsNone(self.manager._candidate) + self.assertIs(self.manager._runtime, current) + + +if __name__ == "__main__": + case = {"half-frame": "scenario_half_frame", "idle": "scenario_idle"}[sys.argv[1]] + result = unittest.TextTestRunner().run(unittest.TestSuite([RecoveryFixture(case)])) + sys.exit(not result.wasSuccessful()) diff --git a/iotdb-core/ainode/tests/test_inference_safety.py b/iotdb-core/ainode/tests/test_inference_safety.py new file mode 100644 index 0000000000000..384e2a108586f --- /dev/null +++ b/iotdb-core/ainode/tests/test_inference_safety.py @@ -0,0 +1,322 @@ +# 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 threading +import time +import unittest +from concurrent.futures import ThreadPoolExecutor +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import test_inference_inputs as input_tests +import torch + +from iotdb.ainode.core.inference.inference_request import ( + InferenceRequest, + InferenceRequestProxy, +) +from iotdb.ainode.core.inference.pool_controller import PoolController +from iotdb.ainode.core.manager.inference_manager import InferenceManager +from iotdb.ainode.core.util.atmoic_int import AtomicInt +from iotdb.ainode.core.util.serde import convert_tensor_to_tsblock +from iotdb.thrift.ainode.ttypes import TForecastReq + + +class InferenceSafetyTest(unittest.TestCase): + def manager(self): + manager = InferenceManager.__new__(InferenceManager) + manager._accepting = True + manager._inflight_slots = threading.BoundedSemaphore(1) + manager._result_wrapper_lock = threading.RLock() + manager._model_manager = MagicMock() + manager._model_manager.is_model_registered.return_value = False + controller = MagicMock() + controller.worker_fault.return_value = None + manager._runtime = SimpleNamespace( + pending={}, controller=controller, fault=None, retired=False + ) + manager._stopping = threading.Event() + manager._wake_watchdog = threading.Event() + return manager + + def controller(self): + with patch("iotdb.ainode.core.inference.pool_controller.ModelManager"): + controller = PoolController(None) + self.addCleanup(lambda: controller.stop(time.monotonic() + 5)) + return controller + + def request(self, name="r", deadline=None): + return InferenceRequest( + name, + "sundial", + inputs=torch.ones(1, 1, 4), + output_length=2, + _deadline=deadline, + ) + + def test_timeout_retains_physical_work_and_late_completion_releases_once(self): + manager = self.manager() + release = MagicMock() + request = self.request(deadline=time.monotonic() + 0.1) + counter = AtomicInt(1) + + def dispatch(req, proxy): + proxy.set_counter(counter) + + runtime = manager._runtime + runtime.controller.add_request.side_effect = dispatch + wait = manager._submit_prepared( + runtime, request.model_id, request.deadline, lambda: request, None, release + ) + with self.assertRaises(TimeoutError): + wait() + self.assertIn(request.req_id, runtime.pending) + self.assertEqual(counter.get(), 1) + release.assert_not_called() + manager._finish_request(runtime, request.req_id, output="done") + manager._finish_request(runtime, request.req_id, output="duplicate") + self.assertEqual(counter.get(), 0) + release.assert_called_once() + + def test_proxy_completion_is_idempotent(self): + proxy = InferenceRequestProxy("r") + counter = AtomicInt(1) + proxy.set_counter(counter) + self.assertTrue(proxy.set_exception(ValueError("first"))) + self.assertFalse(proxy.set_result("late")) + self.assertEqual(counter.get(), 0) + with self.assertRaisesRegex(ValueError, "first"): + proxy.wait_for_result() + + def test_dispatch_failure_releases_work_slot(self): + manager = self.manager() + release = MagicMock() + runtime = manager._runtime + runtime.controller.add_request.side_effect = RuntimeError("unavailable") + with self.assertRaisesRegex(RuntimeError, "unavailable"): + manager._submit_prepared( + runtime, "sundial", None, self.request, None, release + ) + release.assert_called_once() + self.assertFalse(runtime.pending) + + def test_overload_rejects_before_decoding(self): + manager = self.manager() + manager._inflight_slots.acquire() + with patch( + "iotdb.ainode.core.manager.inference_manager.convert_tsblock_to_tensor" + ) as decode: + result = manager.forecast( + TForecastReq(modelId="sundial", inputData=b"", outputLength=2) + ) + self.assertNotEqual(result.status.code, 200) + self.assertIn("capacity", result.status.message) + decode.assert_not_called() + + def test_no_implicit_cpu_fallback_for_managed_model(self): + manager = self.manager() + manager._runtime.controller.has_running_pools.return_value = False + manager._runtime.controller.requires_loaded_pool.return_value = True + module = "iotdb.ainode.core.manager.inference_manager" + with ( + patch( + module + ".convert_tsblock_to_tensor", return_value=torch.ones(1, 1, 4) + ), + patch(module + ".load_pipeline") as load, + ): + result = manager.forecast( + TForecastReq(modelId="sundial", inputData=b"", outputLength=2) + ) + self.assertNotEqual(result.status.code, 200) + load.assert_not_called() + self.assertTrue(manager._inflight_slots.acquire(blocking=False)) + + def test_worker_fault_seals_generation_before_releasing_work(self): + manager = self.manager() + request = self.request() + proxy = InferenceRequestProxy("r") + proxy.assigned_pool_id = 3 + release = MagicMock() + runtime = manager._runtime + runtime.controller.worker_fault.return_value = "worker died" + runtime.pending["r"] = (request, proxy, release) + manager._check_workers() + self.assertFalse(manager._accepting) + manager._finish_request(runtime, "r", output="late") + release.assert_not_called() + runtime.controller.begin_stop.assert_called_once() + manager._finish_request(runtime, "r", error=runtime.fault, retiring=True) + release.assert_called_once() + with self.assertRaisesRegex(Exception, "worker died"): + proxy.wait_for_result() + + def test_completed_request_does_not_misclassify_graceful_unload_as_failure(self): + manager = self.manager() + request = self.request() + proxy = InferenceRequestProxy("r") + proxy.assigned_pool_id = 3 + release = MagicMock() + runtime = manager._runtime + runtime.pending["r"] = (request, proxy, release) + + def worker_check_after_completion(): + manager._finish_request(runtime, "r", output="done") + return None + + runtime.controller.worker_fault.side_effect = worker_check_after_completion + manager._check_workers() + self.assertTrue(manager._accepting) + runtime.controller.begin_stop.assert_not_called() + release.assert_called_once() + + def test_expired_request_is_not_executed_or_grouped(self): + bad = self.request("expired", time.monotonic() - 1) + good = self.request("live", time.monotonic() + 5) + pool = input_tests.InferenceInputsTest().pool([bad, good]) + pool._step() + results = [pool._finished_queue.get_nowait() for _ in range(2)] + self.assertIn("deadline", results[0].error) + self.assertIsNone(results[1].error) + self.assertEqual(len(pool._inference_pipeline.calls[0][0]), 1) + + def test_missing_values_do_not_poison_unrelated_ordinary_request(self): + bad, good = self.request("missing"), self.request("live") + bad.model_inputs[0]["targets"][0, 0] = float("nan") + pool = input_tests.InferenceInputsTest().pool([bad, good]) + pool._step() + results = [pool._finished_queue.get_nowait() for _ in range(2)] + self.assertIn("repaired", results[0].error) + self.assertIsNone(results[1].error) + + def test_lifecycle_command_order_is_not_filtered_by_transient_residency(self): + manager = self.manager() + devices = [torch.device("cpu")] + controller = manager._runtime.controller + controller.has_request_pools.return_value = True + manager.load_model("sundial", devices) + controller.load_model.assert_called_once_with("sundial", devices) + controller.has_request_pools.return_value = False + manager.unload_model("sundial", devices) + controller.unload_model.assert_called_once_with("sundial", devices) + + def test_pending_load_is_managed_before_worker_registration(self): + controller = PoolController.__new__(PoolController) + controller._registry_lock = threading.RLock() + controller._managed_models = set() + controller._desired = {} + controller._stop_event = threading.Event() + controller._transition_counts = {} + controller._task_queue = MagicMock() + controller._request_pool_map = {} + controller.load_model("sundial", [torch.device("cpu")]) + self.assertTrue(controller.requires_loaded_pool("sundial")) + with self.assertRaisesRegex(Exception, "loading or unloading"): + controller.add_request(self.request(), InferenceRequestProxy("r")) + + def test_load_and_recovery_share_one_pool_per_device(self): + controller = PoolController.__new__(PoolController) + controller._registry_lock = threading.RLock() + controller._managed_models = set() + controller._desired = {} + controller._stop_event = threading.Event() + controller._transition_counts = {} + controller._task_queue = MagicMock() + controller._expand_pools_on_device = MagicMock() + controller.worker_fault = MagicMock(return_value=None) + device = torch.device("cpu") + + controller.load_model("sundial", [device]) + controller.load_model("chronos2", [device]) + self.assertEqual(controller._task_queue.put_nowait.call_count, 1) + self.assertEqual(controller.desired_residency()[0], {("sundial", device)}) + + controller.unload_model("sundial", [device]) + controller.load_model("chronos2", [device]) + self.assertEqual(controller._task_queue.put_nowait.call_count, 3) + desired, managed = controller.desired_residency() + self.assertEqual(desired, {("chronos2", device)}) + controller.restore_residency(desired, managed, 123.0) + controller._expand_pools_on_device.assert_called_once_with( + "chronos2", device, 1, 123.0 + ) + + def test_failed_load_preserves_a_newer_queued_load_after_unload(self): + controller = self.controller() + device = torch.device("cpu") + retry_queued = threading.Event() + retry_started = threading.Event() + finish_retry = threading.Event() + after_unload = [] + + def check_memory(_): + if retry_queued.is_set(): + retry_started.set() + finish_retry.wait(5) + else: + controller.unload_model("sundial", [device]) + after_unload.append(controller.desired_residency()) + controller.load_model("sundial", [device]) + retry_queued.set() + return {"free_mem": 0} + + with patch( + "iotdb.ainode.core.manager.utils.evaluate_system_resources", + side_effect=check_memory, + ): + try: + controller.load_model("sundial", [device]) + self.assertTrue(retry_started.wait(5)) + self.assertEqual(after_unload, [(set(), {"sundial"})]) + self.assertEqual( + controller.desired_residency()[0], {("sundial", device)} + ) + self.assertFalse(controller.has_pool_on_device(device)) + finally: + finish_retry.set() + + def test_noop_unload_keeps_cpu_forecast_available(self): + manager = self.manager() + controller = self.controller() + manager._runtime.controller = controller + manager._backend = SimpleNamespace(torch_device=torch.device) + manager._cpu_slot = threading.BoundedSemaphore(1) + device = torch.device("cpu") + request = TForecastReq( + modelId="sundial", + inputData=convert_tensor_to_tsblock(torch.ones(1, 4)), + outputLength=2, + ) + + self.assertEqual(manager.unload_model("sundial", [device]).code, 200) + self.assertEqual(controller.desired_residency(), (set(), set())) + self.assertTrue(controller._task_queue.empty()) + with ( + ThreadPoolExecutor(max_workers=1) as executor, + patch( + "iotdb.ainode.core.manager.inference_manager.load_pipeline", + return_value=input_tests.RecordingPipeline(), + ) as load, + ): + manager._cpu_executor = executor + response = manager.forecast(request) + self.assertEqual(response.status.code, 200, response.status.message) + self.assertEqual(len(response.forecastResult), 1) + load.assert_called_once() + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_lossless_codec.py b/iotdb-core/ainode/tests/test_lossless_codec.py new file mode 100644 index 0000000000000..1046c5c6927b6 --- /dev/null +++ b/iotdb-core/ainode/tests/test_lossless_codec.py @@ -0,0 +1,214 @@ +# 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 os +import unittest +from unittest.mock import patch + +import numpy as np +import torch + +from iotdb.ainode.core.inference.inference_request import InferenceRequest +from iotdb.ainode.core.util import serde + + +class LosslessCodecTest(unittest.TestCase): + def test_default_output_wire_bytes_and_original_errors(self): + for dtype in ( + torch.bool, + torch.int32, + torch.int64, + torch.float32, + torch.float64, + ): + for shape in ((1, 1), (3, 17), (4, 512)): + matrix = torch.arange(shape[0] * shape[1]).reshape(shape).to(dtype) + if dtype.is_floating_point and matrix.numel() >= 4: + matrix.flatten()[:4] = torch.tensor( + [float("nan"), float("inf"), -float("inf"), -0.0], dtype=dtype + ) + for value in (matrix, matrix[:, ::2], matrix.T): + with self.subTest(dtype=dtype, shape=shape, stride=value.stride()): + with patch.dict(os.environ, AINODE_RESULT_CODEC="pandas"): + expected = serde.convert_tensor_to_tsblock(value) + with patch.dict(os.environ), patch.object( + serde.pd, + "DataFrame", + side_effect=AssertionError("used Pandas"), + ): + os.environ.pop("AINODE_RESULT_CODEC", None) + self.assertEqual( + serde.convert_tensor_to_tsblock(value), expected + ) + for value in ( + torch.empty(1, 0), + torch.empty(0, 4), + torch.arange(4), + torch.tensor(1.0), + ): + with self.subTest(shape=value.shape): + with patch.dict(os.environ, AINODE_RESULT_CODEC="pandas"): + expected = serde.convert_tensor_to_tsblock(value) + with patch.dict(os.environ), patch.object( + serde.pd, "DataFrame", wraps=serde.pd.DataFrame + ) as dataframe: + os.environ.pop("AINODE_RESULT_CODEC", None) + self.assertEqual(serde.convert_tensor_to_tsblock(value), expected) + dataframe.assert_called_once() + for value in ( + torch.ones(2, 3, dtype=torch.float16), + torch.ones(2, 3, dtype=torch.bfloat16), + torch.ones(2, 3, requires_grad=True), + torch.ones(1, 2, 3), + ): + with self.subTest(dtype=value.dtype, shape=value.shape): + with patch.dict(os.environ, AINODE_RESULT_CODEC="pandas"): + with self.assertRaises(Exception) as legacy: + serde.convert_tensor_to_tsblock(value) + with patch.dict(os.environ): + os.environ.pop("AINODE_RESULT_CODEC", None) + with self.assertRaises(type(legacy.exception)) as default: + serde.convert_tensor_to_tsblock(value) + self.assertEqual(str(default.exception), str(legacy.exception)) + + def test_input_decode_matches_values_types_shapes_and_signed_zero(self): + arrays = [ + np.array([-0.0, 0.0, np.nan, np.inf, -np.inf, 1e200], dtype=">f8"), + np.array( + [-(2**63), -(2**40) - 1, -1, 0, 2**40 + 1, 2**63 - 1], dtype=">i8" + ), + np.array([True, False, True, False, True, False]), + np.array([], dtype=">f4"), + ] + groups = [[a] for a in arrays] + [[arrays[0], arrays[1]]] + for columns in groups: + outputs = [] + for mode in ("torch", "numpy"): + with patch.dict(os.environ, AINODE_INPUT_CODEC=mode), patch.object( + serde, + "deserialize", + return_value=( + None, + [x.copy() for x in columns], + None, + len(columns[0]), + ), + ): + outputs.append(serde.convert_tsblock_to_tensor(b"fixture")) + expected, actual = outputs + torch.testing.assert_close(actual, expected, rtol=0, atol=0, equal_nan=True) + self.assertEqual(actual.dtype, torch.float32) + self.assertEqual(actual.device.type, "cpu") + np.testing.assert_array_equal( + np.signbit(actual.numpy()), np.signbit(expected.numpy()) + ) + for mode in ("torch", "numpy"): + with patch.dict(os.environ, AINODE_INPUT_CODEC=mode), patch.object( + serde, + "deserialize", + return_value=(None, [np.array(["1", "2"], dtype=object)], None, 2), + ): + with self.assertRaises(TypeError): + serde.convert_tsblock_to_tensor(b"fixture") + + def test_input_decode_preserves_tsblock_positions_with_nulls(self): + columns = [np.array([1.0, 3.0], dtype=">f8"), np.array([2, 4, 6], dtype=">i4")] + nulls = [np.array([False, True, False]), None] + expected = torch.tensor([[[1.0, float("nan"), 3.0], [2.0, 4.0, 6.0]]]) + for mode in ("torch", "numpy"): + with ( + patch.dict(os.environ, AINODE_INPUT_CODEC=mode), + patch.object( + serde, "deserialize", return_value=(None, columns, nulls, 3) + ), + ): + actual = serde.convert_tsblock_to_tensor(b"fixture") + torch.testing.assert_close(actual, expected, equal_nan=True) + + def test_reused_inputs_preserve_request_and_partial_completion(self): + for targets in (1, 3): + raw = torch.arange(targets * 8, dtype=torch.float32).reshape(1, targets, 8) + items = [{"targets": raw[0]}] + default = InferenceRequest( + "r", "model", model_inputs=items, output_length=4, _deadline=1234.0 + ) + reused = InferenceRequest( + "r", + "model", + inputs=raw, + model_inputs=items, + output_length=4, + _deadline=1234.0, + ) + torch.testing.assert_close(default.inputs, reused.inputs, rtol=0, atol=0) + for req in (default, reused): + req.write_step_output(torch.ones(1, targets, 2)) + req.write_step_output(torch.full((1, targets, 2), 2.0)) + torch.testing.assert_close( + default.get_final_output(), reused.get_final_output(), rtol=0, atol=0 + ) + self.assertEqual(default.deadline, reused.deadline) + + def test_forecast_reuses_batch_without_changing_multitarget_response(self): + from test_inference_safety import InferenceSafetyTest + + from iotdb.thrift.ainode.ttypes import TForecastReq + + raw = torch.arange(24, dtype=torch.float32).reshape(3, 8) + encoded = serde.convert_tensor_to_tsblock(raw) + responses = [] + for reuse in ("0", "1"): + manager = InferenceSafetyTest().manager() + + def execute(runtime, model_id, deadline, make_request, cpu_args, release): + req = make_request() + self.assertEqual(tuple(req.inputs.shape), (1, 3, 8)) + release() + return req.inputs[:, :, -4:] + + manager._execute_prepared = execute + with patch.dict(os.environ, AINODE_REUSE_INPUTS=reuse): + if reuse == "1": + with patch( + "torch.stack", side_effect=AssertionError("redundant stack") + ): + response = manager.forecast( + TForecastReq( + modelId="chronos2", + inputData=encoded, + outputLength=4, + options={}, + ) + ) + else: + response = manager.forecast( + TForecastReq( + modelId="chronos2", + inputData=encoded, + outputLength=4, + options={}, + ) + ) + self.assertEqual(response.status.code, 200) + responses.append(response.forecastResult) + self.assertEqual(responses[0], responses[1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_model_loader_fp32.py b/iotdb-core/ainode/tests/test_model_loader_fp32.py new file mode 100644 index 0000000000000..a7a038f5471e0 --- /dev/null +++ b/iotdb-core/ainode/tests/test_model_loader_fp32.py @@ -0,0 +1,141 @@ +# 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 os +import unittest +from contextlib import ExitStack +from types import SimpleNamespace +from unittest.mock import patch + +import torch + +from iotdb.ainode.core.model import fp32_execution, model_loader +from iotdb.ainode.core.model.model_constants import ModelCategory + + +class ModelLoaderFP32Test(unittest.TestCase): + def setUp(self): + patches = ExitStack() + self.addCleanup(patches.close) + patches.enter_context(patch.dict(os.environ, {"AINODE_FP32_EXECUTION": ""})) + self.install = patches.enter_context( + patch.object(fp32_execution, "install_fp32_execution") + ) + self.compile = patches.enter_context(patch.object(torch, "compile")) + patches.enter_context( + patch.object(model_loader, "get_model_path", return_value="models") + ) + self.pt_info = SimpleNamespace( + model_id="local-model", + model_type="pt", + auto_map=None, + hub_mixin_cls="", + category=ModelCategory.BUILTIN, + ) + + def test_pt_default_and_legacy_acceleration(self): + model = torch.nn.Linear(1, 1) + compiled_model = torch.nn.Linear(1, 1) + self.compile.return_value = compiled_model + with ( + patch.object(model_loader.os.path, "exists", return_value=True), + patch.object(torch.jit, "load", return_value=model), + patch.object( + model_loader.BACKEND, "move_model", return_value=compiled_model + ) as move, + ): + self.assertIs(model_loader.load_model(self.pt_info), model) + self.compile.assert_not_called() + move.assert_not_called() + self.assertIs( + model_loader.load_model( + self.pt_info, acceleration=True, device_map="cuda:0" + ), + compiled_model, + ) + self.compile.assert_called_once_with(model) + move.assert_called_once_with(compiled_model, "cuda:0") + self.install.assert_not_called() + + def test_explicit_fp32_replaces_legacy_pt_acceleration(self): + model = torch.nn.Linear(1, 1) + with ( + patch.dict(os.environ, {"AINODE_FP32_EXECUTION": "compile"}), + patch.object(model_loader.os.path, "exists", return_value=True), + patch.object(torch.jit, "load", return_value=model), + patch.object( + model_loader.BACKEND, "move_model", return_value=model + ) as move, + ): + result = model_loader.load_model( + self.pt_info, acceleration=True, device_map="cuda:0" + ) + self.assertIs(result, model) + self.compile.assert_not_called() + move.assert_called_once_with(model, "cuda:0") + self.install.assert_called_once() + self.assertIs(self.install.call_args.args[0], model) + + def test_transformers_load_uses_fp32_only_with_explicit_opt_in(self): + model = torch.nn.Linear(1, 1) + model_info = SimpleNamespace(model_id="hf-model", model_type="hf", auto_map={}) + with patch.object(model_loader, "load_transformers_model", return_value=model): + self.assertIs(model_loader.load_model(model_info, acceleration=True), model) + self.install.assert_not_called() + with patch.dict(os.environ, {"AINODE_FP32_EXECUTION": "compile"}): + self.assertIs(model_loader.load_model(model_info), model) + self.compile.assert_not_called() + self.install.assert_called_once() + self.assertIs(self.install.call_args.args[0], model) + + def test_hub_mixin_load_moves_once_and_uses_explicit_fp32(self): + model = torch.nn.Linear(1, 1) + info = SimpleNamespace( + model_id="toto", + model_type="toto", + auto_map=None, + hub_mixin_cls="modeling_toto.Toto", + ) + model_class = SimpleNamespace(from_pretrained=lambda path: model) + with ( + patch.dict(os.environ, {"AINODE_FP32_EXECUTION": "compile"}), + patch.object( + model_loader, + "get_model_and_config_by_native_code", + return_value=(model_class, None), + ), + patch.object( + model_loader.BACKEND, "move_model", return_value=model + ) as move, + ): + self.assertIs(model_loader.load_model(info, device_map="cuda:0"), model) + move.assert_called_once_with(model, "cuda:0") + self.install.assert_called_once() + self.assertIs(self.install.call_args.args[0], model) + + def test_removed_candidates_are_rejected_even_alongside_compile(self): + with patch.object(model_loader, "_load_torchscript_model") as load_pt: + for candidate in ("graph", "buckets", "autotune"): + with ( + self.subTest(candidate=candidate), + patch.dict( + os.environ, {"AINODE_FP32_EXECUTION": f"compile,{candidate}"} + ), + ): + with self.assertRaisesRegex(ValueError, candidate): + model_loader.load_model(self.pt_info) + load_pt.assert_not_called() diff --git a/iotdb-core/ainode/tests/test_numeric_input_pages.py b/iotdb-core/ainode/tests/test_numeric_input_pages.py new file mode 100644 index 0000000000000..9ecb7d2437aa1 --- /dev/null +++ b/iotdb-core/ainode/tests/test_numeric_input_pages.py @@ -0,0 +1,56 @@ +# 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 unittest +from unittest.mock import patch + +import numpy as np + +from iotdb.utils.iotdb_rpc_dataset import IoTDBRpcDataSet + + +class NumericInputPagesTest(unittest.TestCase): + def test_numeric_sdk_decode_keeps_null_positions_and_default_datetime(self): + dataset = IoTDBRpcDataSet.__new__(IoTDBRpcDataSet) + attrs = { + "ignore_timestamp": True, + "_IoTDBRpcDataSet__column_index_2_tsblock_column_index_list": [0], + "_IoTDBRpcDataSet__query_result_index": 0, + "_IoTDBRpcDataSet__query_result": [b"page"], + "_IoTDBRpcDataSet__data_type_for_tsblock_column": [8], + "_IoTDBRpcDataSet__time_precision": "us", + "_IoTDBRpcDataSet__zone_id": "Asia/Shanghai", + } + for name, value in attrs.items(): + setattr(dataset, name, value) + page = ( + np.arange(3), + [np.array([1001, 3001], dtype=">i8")], + [[False, True, False]], + 3, + ) + with patch("iotdb.utils.iotdb_rpc_dataset.deserialize", return_value=page): + output = dataset._process_buffer()[0][0] + self.assertIsNone(output[1]) + self.assertEqual(output[0].value // 1000000, 1) + self.assertEqual(output[2].value // 1000000, 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_pipeline_transport.py b/iotdb-core/ainode/tests/test_pipeline_transport.py new file mode 100644 index 0000000000000..3254354474301 --- /dev/null +++ b/iotdb-core/ainode/tests/test_pipeline_transport.py @@ -0,0 +1,115 @@ +# 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 os +import pickle +import unittest +from multiprocessing.reduction import ForkingPickler +from unittest.mock import patch + +import numpy as np +import test_inference_inputs as input_tests +import torch + +from iotdb.ainode.core.inference.inference_request import InferenceRequest + + +class PipelineTransportTest(unittest.TestCase): + def request(self): + return InferenceRequest( + "r", + "model", + output_length=4, + model_inputs=[{"targets": torch.tensor([[1.0, float("nan"), 3.0, 4.0]])}], + _deadline=12345.0, + inference_attrs={"batch_size": 3}, + ) + + @patch.dict(os.environ, {"AINODE_REQUEST_IPC": "numpy"}) + def test_small_payload_uses_no_torch_storage_reducer(self): + request = self.request() + with patch( + "torch.multiprocessing.reductions.reduce_storage", + side_effect=AssertionError("storage handle used"), + ): + data = ForkingPickler.dumps(request) + self.assertNotIn(b"rebuild_storage_fd", bytes(data)) + restored = pickle.loads(data) + torch.testing.assert_close( + restored.model_inputs[0]["targets"], + request.model_inputs[0]["targets"], + equal_nan=True, + ) + self.assertEqual(restored.deadline, request.deadline) + self.assertEqual(restored.inference_attrs, request.inference_attrs) + + @patch.dict(os.environ, {"AINODE_REQUEST_IPC": "numpy"}) + def test_partial_output_survives_roundtrip(self): + request = self.request() + request.write_step_output(torch.tensor([[[7.0, 8.0]]])) + restored = pickle.loads(ForkingPickler.dumps(request)) + restored.write_step_output(torch.tensor([[[9.0, 10.0]]])) + torch.testing.assert_close( + restored.get_final_output(), torch.tensor([[[7.0, 8.0, 9.0, 10.0]]]) + ) + self.assertEqual(request.cur_step_idx, 2) + + @patch.dict(os.environ, {"AINODE_REQUEST_IPC": "numpy"}) + def test_large_payload_retains_torch_transport(self): + request = InferenceRequest("r", "model", inputs=torch.ones(1, 1, 100000)) + self.assertNotIn("_cpu_array_ipc", request.__getstate__()) + + @patch.dict(os.environ, {"AINODE_REQUEST_IPC": "numpy"}) + def test_invalid_raw_array_stays_invalid(self): + request = self.request() + request.model_inputs[0]["targets"] = np.ones((1, 4)) + restored = pickle.loads(ForkingPickler.dumps(request)) + self.assertIsInstance(restored.model_inputs[0]["targets"], np.ndarray) + + @patch.dict(os.environ, {"AINODE_REQUEST_IPC": "numpy"}) + def test_bfloat16_retains_dtype_via_torch_fallback(self): + request = InferenceRequest( + "r", "model", inputs=torch.ones(1, 1, 4, dtype=torch.bfloat16) + ) + restored = pickle.loads(ForkingPickler.dumps(request)) + self.assertEqual(restored.inputs.dtype, torch.bfloat16) + + def test_cpu_outputs_never_roundtrip_through_gpu_buffers(self): + request = InferenceRequest( + "r", "model", inputs=torch.ones(1, 1, 4), output_length=2 + ) + pool = input_tests.InferenceInputsTest().pool([request]) + pool.device = torch.device("cuda") + pool._inference_pipeline.input_device = torch.device("cpu") + + def move(value, device): + if torch.device(device).type != "cpu": + raise AssertionError("unnecessary GPU result copy") + return value + + pool._backend.move_tensor = move + pool._step() + result = pool._finished_queue.get_nowait() + self.assertIsNone(result.error) + self.assertEqual(result.get_final_output().device.type, "cpu") + torch.testing.assert_close(result.get_final_output(), torch.ones(1, 1, 2)) + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_process_frontend.py b/iotdb-core/ainode/tests/test_process_frontend.py new file mode 100644 index 0000000000000..e1272da89cae5 --- /dev/null +++ b/iotdb-core/ainode/tests/test_process_frontend.py @@ -0,0 +1,415 @@ +# 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 multiprocessing as mp +import os +import threading +import time +import unittest +from concurrent.futures import ThreadPoolExecutor +from types import SimpleNamespace +from unittest.mock import MagicMock, call, patch + +from iotdb.ainode.core.constant import TSStatusCode +from iotdb.ainode.core.manager.inference_manager import InferenceManager +from iotdb.ainode.core.rpc.process_frontend import ( + BackendBroker, + LeaseRegistry, + ProcessFrontendServer, +) + + +def _stop_with_blocked_cpu_inference(): + import torch + + from iotdb.ainode.core.inference.pipeline.basic_pipeline import ForecastPipeline + from iotdb.ainode.core.util.serde import convert_tensor_to_tsblock + from iotdb.thrift.ainode.ttypes import TForecastReq + + entered = threading.Event() + blocked = threading.Event() + + class BlockedPipeline(ForecastPipeline): + def forecast(self, inputs, **infer_kwargs): + entered.set() + blocked.wait() + + pipeline = BlockedPipeline.__new__(BlockedPipeline) + pipeline.model_info = SimpleNamespace(model_id="blocked") + manager_module = "iotdb.ainode.core.manager.inference_manager" + with ( + patch(f"{manager_module}.ModelManager") as model_manager, + patch("iotdb.ainode.core.inference.pool_controller.ModelManager"), + patch(f"{manager_module}.load_pipeline", return_value=pipeline), + ): + model_manager.return_value.get_model_info.return_value.max_output_length = None + manager = InferenceManager() + try: + response = manager.forecast( + TForecastReq( + modelId="blocked", + inputData=convert_tensor_to_tsblock(torch.ones(1, 4)), + outputLength=1, + options={"_ain_timeout_ms": "1000"}, + ) + ) + if not entered.is_set(): + raise AssertionError(f"CPU pipeline never ran: {response.status}") + if response.status.code != TSStatusCode.AINODE_INTERNAL_ERROR.value: + raise AssertionError(f"Expected timeout: {response.status}") + if manager._cpu_slot.acquire(blocking=False): + raise AssertionError("Blocked inference released its CPU slot") + finally: + manager.stop() + + +class ProcessFrontendTest(unittest.TestCase): + def test_global_capacity_and_exactly_once_completion(self): + registry = LeaseRegistry(1) + self.assertTrue(registry.acquire("a", 10)) + self.assertFalse(registry.acquire("b", 20)) + registry.transfer("a") + self.assertFalse(registry.release("a")) + registry.reap(10) + self.assertFalse(registry.acquire("b", 20)) + self.assertTrue(registry.release("a", True)) + self.assertFalse(registry.release("a", True)) + self.assertTrue(registry.acquire("b", 20)) + registry.reap(20) + self.assertTrue(registry.acquire("c", 30)) + + def test_duplicate_submission_never_executes_twice(self): + registry = LeaseRegistry(2) + registry.acquire("a", 10) + registry.transfer("a") + with self.assertRaises(RuntimeError): + registry.transfer("a") + self.assertEqual(len(registry.leases), 1) + + def test_backend_timeout_retains_lease_until_physical_completion(self): + broker = BackendBroker.__new__(BackendBroker) + broker.admission = LeaseRegistry(1) + + def submit(runtime, model_id, deadline, make_request, cpu_args, release): + self.release = release + + def wait(): + raise TimeoutError("caller timed out") + + return wait + + broker.manager = SimpleNamespace( + _result_wrapper_lock=threading.RLock(), + _runtime=None, + _require_available=lambda: None, + _submit_prepared=submit, + ) + broker.admission.acquire("a", 10) + with self.assertRaises(TimeoutError): + broker.infer("a", SimpleNamespace(model_id="m", deadline=None)) + broker.abandon("a") + broker.admission.reap(10) + self.assertFalse(broker.admission.acquire("b", 20)) + self.release() + self.assertTrue(broker.admission.acquire("b", 20)) + + def test_cpu_fallback_timeout_retains_one_worker_and_admission(self): + gate = threading.Event() + released = threading.Event() + broker = BackendBroker.__new__(BackendBroker) + broker.admission = LeaseRegistry(1) + release = broker.admission.release + + def release_and_signal(key, backend_done=False): + result = release(key, backend_done) + if backend_done: + released.set() + return result + + broker.admission.release = release_and_signal + controller = SimpleNamespace( + has_running_pools=lambda _: False, requires_loaded_pool=lambda _: False + ) + manager = InferenceManager.__new__(InferenceManager) + manager._accepting = True + manager._result_wrapper_lock = threading.RLock() + manager._runtime = SimpleNamespace(controller=controller, pending={}) + manager._cpu_slot = threading.BoundedSemaphore(1) + manager._run_cpu = lambda *args: gate.wait(2) + broker.manager = manager + broker.admission.acquire("a", 10, manager._runtime) + req = SimpleNamespace( + model_id="m", + restore_cpu_payload=lambda: None, + inference_attrs={}, + model_inputs=[], + output_length=1, + deadline=time.monotonic() + 0.02, + ) + try: + with self.assertRaises(TimeoutError): + broker.infer("a", req) + self.assertFalse(broker.manager._cpu_slot.acquire(blocking=False)) + broker.abandon("a") + self.assertFalse(broker.admission.acquire("b", 20)) + finally: + gate.set() + self.assertTrue(released.wait(timeout=3)) + self.assertTrue(broker.manager._cpu_slot.acquire(blocking=False)) + self.assertTrue(broker.admission.acquire("b", 20)) + + def test_process_exits_after_shutdown_with_blocked_cpu_inference(self): + process = mp.get_context("spawn").Process( + target=_stop_with_blocked_cpu_inference + ) + process.start() + try: + process.join(timeout=30) + self.assertEqual( + process.exitcode, 0, "AINode subprocess failed to exit cleanly" + ) + finally: + if process.is_alive(): + process.kill() + process.join(timeout=5) + if not process.is_alive(): + process.close() + + def test_external_stop_and_serve_finally_reap_frontend_after_kill(self): + handler = MagicMock() + server = ProcessFrontendServer(handler, 1) + server.broker = MagicMock() + server.listener = listener = MagicMock() + server.server = broker_server = MagicMock() + server.directory = directory = MagicMock() + process = MagicMock(pid=123, exitcode=None) + server.processes.append(process) + + killed = threading.Event() + ready = threading.Event() + process.kill.side_effect = killed.set + + def join(timeout): + self.assertIn(process, server.processes) + if killed.is_set(): + process.exitcode = -9 + + process.join.side_effect = join + with ( + patch.object(server, "_start"), + patch.object(server, "_spawn", side_effect=ready.set), + ThreadPoolExecutor(max_workers=1) as executor, + ): + serving = executor.submit(server.serve) + try: + self.assertTrue(ready.wait(timeout=5)) + finally: + server.stop() + serving.result(timeout=5) + + self.assertEqual( + process.method_calls, + [ + call.join(timeout=10), + call.terminate(), + call.join(timeout=5), + call.kill(), + call.join(timeout=5), + ], + ) + self.assertEqual(server.processes, []) + server.broker.reap.assert_called_once_with(123) + handler.begin_stop.assert_called_once_with() + listener.close.assert_called_once_with() + broker_server.stop_event.set.assert_called_once_with() + broker_server.listener.close.assert_called_once_with() + directory.cleanup.assert_called_once_with() + + def test_spawned_frontends_share_one_backend_and_restart_after_failure(self): + self._spawn_case() + + def test_ipv6_frontends_keep_compact_protocol(self): + self._spawn_case(host="::1", compressed=True) + + def test_frontends_preserve_mutual_tls_configuration(self): + self._spawn_case(tls=True) + + def _spawn_case(self, host="127.0.0.1", compressed=False, tls=False): + import ssl + import subprocess + import tempfile + from pathlib import Path + + import numpy as np + import torch + from thrift.protocol import TBinaryProtocol, TCompactProtocol + from thrift.transport import TSocket, TSSLSocket, TTransport + + from iotdb.ainode.core.config import AINodeDescriptor + from iotdb.ainode.core.util.serde import ( + convert_tensor_to_tsblock, + convert_tsblock_to_tensor, + ) + from iotdb.thrift.ainode import IAINodeRPCService + from iotdb.thrift.ainode.ttypes import TForecastReq + from iotdb.thrift.common.ttypes import TSStatus + + config = AINodeDescriptor().get_config() + previous = vars(config).copy() + config.set_ain_rpc_port(0) + config.set_ain_rpc_address(host) + config.set_ain_thrift_compression_enabled(int(compressed)) + cert_directory = tempfile.TemporaryDirectory(prefix="ain-fp-tls-") + cert = Path(cert_directory.name) / "cert.pem" + key = Path(cert_directory.name) / "key.pem" + if tls: + subprocess.run( + [ + "openssl", + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + str(key), + "-out", + str(cert), + "-days", + "1", + "-subj", + "/CN=localhost", + "-addext", + "subjectAltName=DNS:localhost,IP:127.0.0.1", + ], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=True, + ) + config.set_ain_internal_ssl_enabled(1) + config.set_ain_thrift_ssl_cert_file(str(cert)) + config.set_ain_thrift_ssl_key_file(str(key)) + calls = [] + + def infer(req, release): + # This in-process stand-in consumes the input where a real model + # worker would deserialize the request and restore CPU tensors. + req.restore_cpu_payload() + self.assertIs(req.inference_attrs["predict_batches_jointly"], False) + calls.append(req.req_id) + release() + return req.inputs[:, :, : req.output_length] * int( + req.inference_attrs["scale"] + ) + + manager = SimpleNamespace( + _result_wrapper_lock=threading.RLock(), + _runtime=None, + _require_available=lambda: None, + _max_output_length=lambda _: config.get_ain_inference_max_output_length(), + _submit_prepared=lambda runtime, model, deadline, request, cpu, release: lambda: infer( + request(), release + ), + ) + handler = SimpleNamespace( + _inference_manager=manager, + _ensure_model_is_registered=lambda _: TSStatus(code=200), + stop=lambda: None, + ) + server = ProcessFrontendServer(handler, 2) + errors = [] + + def serve(): + try: + server.serve() + except Exception as error: + errors.append(str(error)) + + thread = threading.Thread(target=serve, daemon=True) + + def forecast(): + port = server.listener.getsockname()[1] + if tls: + context = ssl.create_default_context(cafile=str(cert)) + context.check_hostname = False + context.load_cert_chain(str(cert), str(key)) + socket = TSSLSocket.TSSLSocket(host, port, ssl_context=context) + else: + socket = TSocket.TSocket(host, port) + socket.setTimeout(10000) + transport = TTransport.TFramedTransport(socket) + transport.open() + try: + reply = IAINodeRPCService.Client( + ( + TCompactProtocol.TCompactProtocol + if compressed + else TBinaryProtocol.TBinaryProtocol + )(transport) + ).forecast( + TForecastReq( + modelId="m", + inputData=convert_tensor_to_tsblock( + torch.arange(4, dtype=torch.float32).reshape(1, 4) + ), + outputLength=2, + options={"predict_batches_jointly": "false", "scale": "2"}, + ) + ) + self.assertEqual(reply.status.code, 200, reply.status) + np.testing.assert_allclose( + convert_tsblock_to_tensor(reply.forecastResult[0]).numpy(), + [[[0, 2]]], + ) + finally: + transport.close() + + try: + with patch.dict( + os.environ, AINODE_REQUEST_IPC="numpy", AINODE_RESULT_CODEC="numpy" + ): + thread.start() + deadline = time.monotonic() + 70 + while len(server.processes) < 2 or not all( + p.is_alive() for p in server.processes + ): + if errors or time.monotonic() > deadline: + self.fail(str(errors)) + time.sleep(0.1) + with ThreadPoolExecutor(max_workers=8) as pool: + list(pool.map(lambda _: forecast(), range(16))) + old = server.processes[0].pid + server.processes[0].terminate() + while any(p.pid == old for p in server.processes): + if errors or time.monotonic() > deadline: + self.fail(str(errors)) + time.sleep(0.1) + forecast() + self.assertFalse(server.broker.admission.leases) + self.assertEqual(len(calls), 17) + finally: + server.stop() + thread.join(timeout=30) + vars(config).clear() + vars(config).update(previous) + cert_directory.cleanup() + self.assertFalse(errors, errors) + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_request_pipe.py b/iotdb-core/ainode/tests/test_request_pipe.py new file mode 100644 index 0000000000000..6cb98dcf122be --- /dev/null +++ b/iotdb-core/ainode/tests/test_request_pipe.py @@ -0,0 +1,65 @@ +# 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 os +import sys +import unittest +from unittest.mock import MagicMock, patch + +from iotdb.ainode.core.inference.pool_controller import configure_request_pipe + + +class RequestPipeTest(unittest.TestCase): + @patch.dict(os.environ, {"AINODE_REQUEST_PIPE_BYTES": "0"}) + def test_default_does_not_change_queue(self): + queue = MagicMock() + self.assertIsNone(configure_request_pipe(queue)) + queue._writer.fileno.assert_not_called() + + @unittest.skipUnless(sys.platform.startswith("linux"), "Linux pipe capacity") + @patch.dict(os.environ, {"AINODE_REQUEST_PIPE_BYTES": "524288"}) + def test_capacity_is_applied_to_own_pipe(self): + import fcntl + import multiprocessing + + queue = multiprocessing.get_context("spawn").Queue() + try: + actual = configure_request_pipe(queue) + if actual is None: + self.skipTest("Pipe resizing is not permitted by this platform") + self.assertGreaterEqual(actual, 524288) + self.assertEqual( + fcntl.fcntl(queue._reader.fileno(), fcntl.F_GETPIPE_SZ), actual + ) + finally: + queue.close() + queue.join_thread() + + @unittest.skipUnless(sys.platform.startswith("linux"), "Linux pipe capacity") + @patch.dict(os.environ, {"AINODE_REQUEST_PIPE_BYTES": "524288"}) + def test_denied_resize_keeps_platform_queue(self): + with patch("fcntl.fcntl", side_effect=PermissionError("denied")): + self.assertIsNone(configure_request_pipe(MagicMock())) + + @patch.dict(os.environ, {"AINODE_REQUEST_PIPE_BYTES": "2097152"}) + def test_unbounded_pipe_setting_is_rejected(self): + with self.assertRaises(ValueError): + configure_request_pipe(MagicMock()) + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_request_transfer.py b/iotdb-core/ainode/tests/test_request_transfer.py new file mode 100644 index 0000000000000..fd14560710dce --- /dev/null +++ b/iotdb-core/ainode/tests/test_request_transfer.py @@ -0,0 +1,171 @@ +# 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 os +import pickle +import threading +import time +import unittest +from concurrent.futures import ThreadPoolExecutor +from multiprocessing.reduction import ForkingPickler +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import numpy as np +import test_pipeline_transport as transport +import torch + +from iotdb.ainode.core.inference.inference_request import ( + InferenceRequest, + InferenceRequestTransfer, +) +from iotdb.ainode.core.manager.inference_manager import InferenceManager +from iotdb.ainode.core.rpc.process_frontend import BackendBroker + + +class RequestTransferTest(unittest.TestCase): + @patch.dict(os.environ, {"AINODE_REQUEST_IPC": "numpy"}) + def test_router_keeps_arrays_and_worker_restores_tensors_once(self): + original = transport.PipelineTransportTest().request() + envelope = InferenceRequestTransfer.from_request(original) + self.assertIsInstance(envelope, InferenceRequestTransfer) + first_wire = ForkingPickler.dumps(envelope) + with patch( + "torch.from_numpy", side_effect=AssertionError("router rebuilt tensor") + ): + router_request = pickle.loads(first_wire).into_request() + second_wire = ForkingPickler.dumps(router_request) + worker_request = pickle.loads(second_wire) + torch.testing.assert_close( + worker_request.inputs, original.inputs, equal_nan=True + ) + torch.testing.assert_close( + worker_request.model_inputs[0]["targets"], + original.model_inputs[0]["targets"], + equal_nan=True, + ) + self.assertEqual(worker_request.inference_attrs, original.inference_attrs) + self.assertEqual(worker_request.deadline, original.deadline) + self.assertEqual(worker_request.req_id, original.req_id) + self.assertNotIn("_cpu_array_ipc", worker_request.__dict__) + + @patch.dict(os.environ, {"AINODE_REQUEST_IPC": "numpy"}) + def test_partial_output_and_snapshot_isolation_survive_two_hops(self): + original = InferenceRequest( + "r", "model", inputs=torch.ones(1, 1, 4), output_length=4 + ) + original.write_step_output(torch.tensor([[[7.0, 8.0]]])) + envelope = InferenceRequestTransfer.from_request(original) + original.inputs.fill_(100) + worker = pickle.loads( + ForkingPickler.dumps( + pickle.loads(ForkingPickler.dumps(envelope)).into_request() + ) + ) + torch.testing.assert_close(worker.inputs, torch.ones(1, 1, 4)) + worker.write_step_output(torch.tensor([[[9.0, 10.0]]])) + torch.testing.assert_close( + worker.get_final_output(), torch.tensor([[[7.0, 8.0, 9.0, 10.0]]]) + ) + self.assertEqual(original.cur_step_idx, 2) + + @patch.dict(os.environ, {"AINODE_REQUEST_IPC": "numpy"}) + def test_large_and_unsupported_payloads_retain_legacy_transport(self): + for request in [ + InferenceRequest("big", "model", inputs=torch.ones(1, 1, 100000)), + InferenceRequest( + "bf16", "model", inputs=torch.ones(1, 1, 4, dtype=torch.bfloat16) + ), + ]: + self.assertIs(InferenceRequestTransfer.from_request(request), request) + + @patch.dict(os.environ, {"AINODE_REQUEST_IPC": "torch"}) + def test_default_torch_transport_is_unchanged(self): + request = transport.PipelineTransportTest().request() + self.assertIs(InferenceRequestTransfer.from_request(request), request) + + @patch.dict(os.environ, {"AINODE_REQUEST_IPC": "numpy"}) + def test_invalid_numpy_target_input_is_not_implicitly_accepted(self): + request = transport.PipelineTransportTest().request() + request.model_inputs[0]["targets"] = np.ones((1, 4)) + router = InferenceRequestTransfer.from_request(request).into_request() + worker = pickle.loads(ForkingPickler.dumps(router)) + self.assertIsInstance(worker.model_inputs[0]["targets"], np.ndarray) + + def broker(self, executor, run_cpu): + manager = InferenceManager.__new__(InferenceManager) + manager._accepting = True + manager._result_wrapper_lock = threading.RLock() + controller = MagicMock() + controller.has_running_pools.return_value = False + controller.requires_loaded_pool.return_value = False + manager._runtime = SimpleNamespace(controller=controller, pending={}) + manager._cpu_slot = threading.BoundedSemaphore(1) + manager._cpu_executor = executor + manager._run_cpu = run_cpu + broker = BackendBroker.__new__(BackendBroker) + broker.manager = manager + broker.admission = MagicMock() + return broker + + @patch.dict(os.environ, {"AINODE_REQUEST_IPC": "numpy"}) + def test_cpu_fallback_restores_before_model_use_and_releases_once(self): + request = InferenceRequest( + "r", + "cpu", + inputs=torch.ones(1, 1, 4), + output_length=2, + _deadline=time.monotonic() + 5, + ) + + def run_cpu(model_id, inputs, length, attrs): + self.assertIsInstance(inputs[0]["targets"], torch.Tensor) + return inputs[0]["targets"][:, :length] + + with ThreadPoolExecutor(max_workers=1) as executor: + broker = self.broker(executor, run_cpu) + result = broker.infer("key", InferenceRequestTransfer.from_request(request)) + np.testing.assert_array_equal(result, np.ones((1, 2))) + broker.admission.release.assert_called_once_with("key", backend_done=True) + self.assertTrue(broker.manager._cpu_slot.acquire(blocking=False)) + + @patch.dict(os.environ, {"AINODE_REQUEST_IPC": "numpy"}) + def test_restore_failure_releases_cpu_and_admission(self): + request = InferenceRequest( + "r", + "cpu", + inputs=torch.ones(1, 1, 4), + output_length=2, + _deadline=time.monotonic() + 5, + ) + with ThreadPoolExecutor(max_workers=1) as executor: + broker = self.broker(executor, MagicMock()) + with patch.object( + InferenceRequest, + "restore_cpu_payload", + side_effect=ValueError("bad state"), + ): + with self.assertRaisesRegex(ValueError, "bad state"): + broker.infer("key", InferenceRequestTransfer.from_request(request)) + broker.admission.release.assert_called_once_with("key", backend_done=True) + self.assertTrue(broker.manager._cpu_slot.acquire(blocking=False)) + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_resource_controls.py b/iotdb-core/ainode/tests/test_resource_controls.py new file mode 100644 index 0000000000000..3d2cbfc3297f1 --- /dev/null +++ b/iotdb-core/ainode/tests/test_resource_controls.py @@ -0,0 +1,56 @@ +# 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 threading +import unittest +from unittest.mock import MagicMock, patch + +import torch + +from iotdb.ainode.core.inference.inference_request_pool import PoolState +from iotdb.ainode.core.inference.pool_controller import PoolController +from iotdb.ainode.core.manager.utils import evaluate_system_resources + + +class ResourceControlsTest(unittest.TestCase): + def test_memory_query_uses_requested_cuda_device(self): + device = torch.device("cuda:1") + with patch("torch.cuda.mem_get_info", return_value=(123, 456)) as memory: + result = evaluate_system_resources(device) + memory.assert_called_once_with(device) + self.assertEqual(result["total_mem"], 456) + + def test_unload_wait_yields_cpu_until_busy_pool_drains(self): + controller = PoolController.__new__(PoolController) + controller._registry_lock = threading.RLock() + controller.get_pool_ids = MagicMock(return_value=[0]) + controller.get_load = MagicMock(side_effect=[1, 1, 0]) + controller.get_state = MagicMock(return_value=PoolState.RUNNING) + controller.set_state = MagicMock() + controller.get_request_pool = MagicMock() + controller._erase_pool = MagicMock() + controller._stop_event = MagicMock() + controller._stop_event.is_set.return_value = False + controller._shrink_pools_on_device("chronos2", torch.device("cpu"), 1) + controller._stop_event.wait.assert_called_once_with(0.01) + controller._erase_pool.assert_called_once_with( + "chronos2", torch.device("cpu"), 0 + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_rle_expansion.py b/iotdb-core/ainode/tests/test_rle_expansion.py new file mode 100644 index 0000000000000..502e8457679c8 --- /dev/null +++ b/iotdb-core/ainode/tests/test_rle_expansion.py @@ -0,0 +1,58 @@ +# 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 unittest + +import numpy as np + +from iotdb.tsfile.utils.tsblock_serde import repeat + + +class RleExpansionTest(unittest.TestCase): + def test_numeric_scalar_expansion_preserves_exact_encoded_bits(self): + for dtype in (">i4", "i8", "f4", "f8", "f4", copy=False).tobytes(), encoded * 512 + ) + + def test_boolean_text_and_empty_inputs_keep_existing_behavior(self): + for kind, value in [ + (0, np.array([True])), + (5, np.array([b"abc"], dtype=object)), + ]: + actual = repeat(value, kind, 4) + self.assertEqual(actual.tolist(), [value[0]] * 4) + self.assertEqual(repeat(np.array([], dtype=">i8"), 2, 512).size, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_rpc_array_output.py b/iotdb-core/ainode/tests/test_rpc_array_output.py new file mode 100644 index 0000000000000..4e4533db4dfad --- /dev/null +++ b/iotdb-core/ainode/tests/test_rpc_array_output.py @@ -0,0 +1,120 @@ +# 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 os +import queue +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +import numpy as np +import torch + +from iotdb.ainode.core.inference.inference_request import InferenceResult +from iotdb.ainode.core.manager.inference_manager import InferenceManager +from iotdb.ainode.core.util import serde + + +class RpcArrayOutputTest(unittest.TestCase): + def test_tensor_api_unchanged_and_rpc_array_avoids_tensor_creation(self): + values = np.arange(24, dtype=np.float32).reshape(1, 3, 8) + result = InferenceResult("r", values) + self.assertIsInstance(result.get_final_output(), torch.Tensor) + with patch("torch.from_numpy", side_effect=AssertionError("redundant Tensor")): + self.assertIs(result.get_rpc_output(), values) + failed = InferenceResult("r", None, "failed") + for method in (failed.get_rpc_output, failed.get_final_output): + with self.assertRaisesRegex(ValueError, "Failed inference"): + method() + + def test_native_array_default_wire_encoding_matches_explicit_pandas(self): + for dtype in (np.bool_, np.int32, np.int64, np.float32, np.float64): + values = np.arange(24).reshape(3, 8).astype(dtype) + if np.issubdtype(dtype, np.floating): + values[0, :4] = [np.nan, np.inf, -np.inf, -0.0] + elif dtype is np.bool_: + values.view(np.uint8)[0, 2] = 0xFF + for array in (values, values[:, ::2], values.T, values[:, :0], values[0]): + with self.subTest( + dtype=dtype, shape=array.shape, strides=array.strides + ): + with patch.dict( + os.environ, AINODE_RESULT_CODEC="pandas" + ), patch.object( + serde.pd, "DataFrame", wraps=serde.pd.DataFrame + ) as pandas_dataframe: + reference = serde.convert_tensor_to_tsblock(array) + pandas_dataframe.assert_called_once() + with patch.dict(os.environ), patch.object( + serde.pd, "DataFrame", wraps=serde.pd.DataFrame + ) as dataframe: + os.environ.pop("AINODE_RESULT_CODEC", None) + self.assertEqual( + serde.convert_tensor_to_tsblock(array), reference + ) + self.assertEqual( + dataframe.call_count, int(array.ndim != 2 or not array.size) + ) + for invalid in ( + np.ones((2, 3), dtype=np.dtype(np.float32).newbyteorder("S")), + np.ones((1, 2, 3)), + np.array(1.0), + ): + with self.subTest(dtype=invalid.dtype, shape=invalid.shape): + with patch.dict(os.environ, AINODE_RESULT_CODEC="pandas"): + with self.assertRaises(Exception) as legacy: + serde.convert_tensor_to_tsblock(invalid) + with patch.dict(os.environ): + os.environ.pop("AINODE_RESULT_CODEC", None) + with self.assertRaises(type(legacy.exception)) as default: + serde.convert_tensor_to_tsblock(invalid) + self.assertEqual(str(default.exception), str(legacy.exception)) + + def test_result_handler_selects_array_without_changing_completion(self): + for mode in (None, "numpy"): + manager = InferenceManager.__new__(InferenceManager) + results = queue.Queue() + runtime = SimpleNamespace( + queue=SimpleNamespace(get=results.get_nowait), + controller=SimpleNamespace(stopping=True), + ) + values = np.arange(8, dtype=np.float32).reshape(1, 1, 8) + results.put(InferenceResult("r", values)) + completed = [] + + def finish(runtime, req_id, output, error): + completed.append((req_id, output, error)) + + manager._finish_request = finish + with patch.dict(os.environ): + if mode is None: + os.environ.pop("AINODE_RESULT_FORMAT", None) + else: + os.environ["AINODE_RESULT_FORMAT"] = mode + manager._handle_results(runtime) + self.assertEqual(completed[0][0], "r") + self.assertIsNone(completed[0][2]) + self.assertIsInstance( + completed[0][1], np.ndarray if mode == "numpy" else torch.Tensor + ) + np.testing.assert_array_equal(np.asarray(completed[0][1]), values) + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_rpc_connections.py b/iotdb-core/ainode/tests/test_rpc_connections.py new file mode 100644 index 0000000000000..4fe4f27d9f8d5 --- /dev/null +++ b/iotdb-core/ainode/tests/test_rpc_connections.py @@ -0,0 +1,96 @@ +# 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 threading +import time +import unittest +from types import SimpleNamespace + +from thrift.protocol import TBinaryProtocol +from thrift.transport import TSocket, TTransport + +from iotdb.ainode.core.rpc.service import AINodeThreadPoolServer +from iotdb.thrift.ainode import IAINodeRPCService +from iotdb.thrift.ainode.ttypes import TShowAIDevicesResp +from iotdb.thrift.common.ttypes import TSStatus + + +class RPCConnectionsTest(unittest.TestCase): + def setUp(self): + handler = SimpleNamespace( + showAIDevices=lambda: TShowAIDevicesResp( + status=TSStatus(code=200), deviceIdMap={"cpu": "cpu"} + ) + ) + transport = TSocket.TServerSocket(host="127.0.0.1", port=0) + self.server = AINodeThreadPoolServer( + IAINodeRPCService.Processor(handler), + transport, + TTransport.TFramedTransportFactory(), + TBinaryProtocol.TBinaryProtocolFactory(), + daemon=True, + max_clients=16, + ) + self.thread = threading.Thread(target=self.server.serve, daemon=True) + self.thread.start() + deadline = time.monotonic() + 5 + while transport.handle is None: + if time.monotonic() >= deadline: + self.fail("RPC listener did not start") + time.sleep(0.01) + self.port = transport.handle.getsockname()[1] + self.transports = [] + + def connect(self): + socket = TSocket.TSocket("127.0.0.1", self.port) + socket.setTimeout(1000) + transport = TTransport.TFramedTransport(socket) + transport.open() + self.transports.append(transport) + return IAINodeRPCService.Client(TBinaryProtocol.TBinaryProtocol(transport)) + + def tearDown(self): + for transport in self.transports: + transport.close() + self.server.stop() + self.thread.join(timeout=2) + self.assertFalse(self.thread.is_alive()) + + def test_idle_connections_do_not_starve_new_rpc(self): + # Old TThreadPoolServer stalls once its ten workers own these sockets. + for _ in range(12): + self.assertEqual(self.connect().showAIDevices().status.code, 200) + self.assertEqual(self.connect().showAIDevices().deviceIdMap, {"cpu": "cpu"}) + + def test_limit_rejects_promptly_and_released_slot_is_reusable(self): + for _ in range(16): + self.assertEqual(self.connect().showAIDevices().status.code, 200) + with self.assertRaises(TTransport.TTransportException): + self.connect().showAIDevices() + self.transports[0].close() + deadline = time.monotonic() + 2 + while len(self.server._clients) == 16 and time.monotonic() < deadline: + time.sleep(0.01) + self.assertEqual(self.connect().showAIDevices().status.code, 200) + + def test_nonpositive_connection_limit_is_invalid(self): + with self.assertRaises(ValueError): + AINodeThreadPoolServer(None, None, max_clients=0) + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_rpc_frame_limits.py b/iotdb-core/ainode/tests/test_rpc_frame_limits.py new file mode 100644 index 0000000000000..25a009985f630 --- /dev/null +++ b/iotdb-core/ainode/tests/test_rpc_frame_limits.py @@ -0,0 +1,192 @@ +# 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 os +import socket +import threading +import unittest +from struct import pack +from types import SimpleNamespace +from unittest.mock import patch + +from thrift.protocol import TBinaryProtocol, TCompactProtocol +from thrift.transport import TSocket, TTransport + +from iotdb.ainode.core.config import AINodeConfig, AINodeDescriptor +from iotdb.ainode.core.constant import AINODE_CONF_FILE_NAME +from iotdb.ainode.core.rpc.framed_transport import ( + BoundedFramedTransport, + BoundedFramedTransportFactory, +) +from iotdb.ainode.core.rpc.service import AINodeRPCService +from iotdb.thrift.ainode import IAINodeRPCService +from iotdb.thrift.ainode.ttypes import TInferenceReq, TInferenceResp +from iotdb.thrift.common.ttypes import TSStatus + + +class FrameLimitsTest(unittest.TestCase): + def test_rejects_size_before_reading_payload(self): + for declared_size, error_type in ( + (-1, TTransport.TTransportException.NEGATIVE_SIZE), + (129, TTransport.TTransportException.SIZE_LIMIT), + ): + source = TTransport.TMemoryBuffer(pack("!i", declared_size) + b"untouched") + transport = BoundedFramedTransport(source, 128) + with self.assertRaises(TTransport.TTransportException) as raised: + transport.read(1) + self.assertEqual(raised.exception.type, error_type) + self.assertEqual(source.read(9), b"untouched") + + def test_exact_boundary_and_fast_reader_across_frames(self): + source = TTransport.TMemoryBuffer( + pack("!i", 3) + b"abc" + pack("!i", 3) + b"def" + ) + transport = BoundedFramedTransportFactory(3).getTransport(source) + self.assertEqual(transport.read(2), b"ab") + self.assertEqual( + transport.cstringio_refill(transport.cstringio_buf.read(), 4).read(), + b"cdef", + ) + + def test_empty_frame_and_standard_writer_remain_compatible(self): + source = TTransport.TMemoryBuffer(pack("!i", 0) + pack("!i", 1) + b"x") + transport = BoundedFramedTransport(source, 1) + self.assertEqual(transport.read(1), b"") + self.assertEqual(transport.read(1), b"x") + output = TTransport.TMemoryBuffer() + writer = BoundedFramedTransport(output, 1) + writer.write(b"payload") + writer.flush() + self.assertEqual(output.getvalue(), pack("!i", 7) + b"payload") + + def test_config_defaults_and_invalid_values(self): + config = AINodeConfig() + self.assertEqual(config.get_ain_rpc_max_frame_size(), 16384000) + self.assertEqual(config.get_ain_config_node_max_frame_size(), 16384000) + self.assertEqual(config.get_ain_inference_max_output_length(), 2880) + for invalid in (0, -1, 0x40000000): + with self.subTest(value=invalid): + for setter in ( + config.set_ain_rpc_max_frame_size, + config.set_ain_config_node_max_frame_size, + BoundedFramedTransportFactory, + ): + with self.assertRaises(ValueError): + setter(invalid) + for invalid in (0, -1): + with self.assertRaises(ValueError): + config.set_ain_inference_max_output_length(invalid) + + def load_config(self, properties): + descriptor = AINodeDescriptor() + config = AINodeConfig() + module = "iotdb.ainode.core.config" + with ( + patch.object(descriptor, "_config", config), + patch( + module + ".os.path.exists", + side_effect=lambda value: os.fspath(value).endswith( + AINODE_CONF_FILE_NAME + ), + ), + patch(module + ".load_properties", return_value=properties), + ): + descriptor._load_config_from_file() + return config + + def test_limits_are_loaded_from_properties(self): + config = self.load_config( + { + "ain_rpc_max_frame_size": "33554432", + "ain_config_node_max_frame_size": "1048576", + "ain_inference_max_output_length": "8192", + } + ) + self.assertEqual(config.get_ain_rpc_max_frame_size(), 33554432) + self.assertEqual(config.get_ain_config_node_max_frame_size(), 1048576) + self.assertEqual(config.get_ain_inference_max_output_length(), 8192) + + def test_invalid_file_limits_fail_startup(self): + for key in ( + "ain_rpc_max_frame_size", + "ain_config_node_max_frame_size", + "ain_inference_max_output_length", + ): + for value in ("0", "-1", "not-an-integer"): + with self.subTest(key=key, value=value): + with self.assertRaises(ValueError): + self.load_config({key: value}) + + def test_real_rpc_above_old_limit_with_both_protocols(self): + payload = b"x" * 16384001 + max_frame_size = 32 * 1024 * 1024 + for compressed, protocol_type in ( + (False, TBinaryProtocol.TBinaryProtocol), + (True, TCompactProtocol.TCompactProtocol), + ): + with self.subTest(protocol=protocol_type.__name__): + seen = [] + + def inference(request): + seen.append((request.modelId, len(request.dataset))) + return TInferenceResp( + status=TSStatus(code=200), + inferenceResult=[request.dataset], + ) + + config = AINodeConfig() + config.set_ain_rpc_max_frame_size(max_frame_size) + config.set_ain_thrift_compression_enabled(compressed) + with ( + patch.dict(os.environ, AINODE_FRONTEND_PROCESSES="0"), + patch.object(AINodeDescriptor(), "_config", config), + socket.socket() as listener, + ): + listener.bind(("127.0.0.1", 0)) + listener.listen() + connection = TSocket.TSocket("127.0.0.1", listener.getsockname()[1]) + connection.setTimeout(5000) + transport = BoundedFramedTransport(connection, max_frame_size) + server = AINodeRPCService( + SimpleNamespace(inference=inference, stop=lambda: None) + ) + thread = threading.Thread( + target=server.serve_inherited, + args=(listener, threading.BoundedSemaphore(2)), + daemon=True, + ) + thread.start() + try: + transport.open() + client = IAINodeRPCService.Client( + protocol_type(transport, string_length_limit=max_frame_size) + ) + result = client.inference( + TInferenceReq(modelId="frame-test", dataset=payload) + ) + self.assertEqual(result.status.code, 200) + self.assertEqual(result.inferenceResult, [payload]) + self.assertEqual(seen, [("frame-test", len(payload))]) + finally: + transport.close() + server.stop() + thread.join(timeout=3) + self.assertFalse(thread.is_alive()) + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/ainode/tests/test_serving_optimization.py b/iotdb-core/ainode/tests/test_serving_optimization.py new file mode 100644 index 0000000000000..ab23494632449 --- /dev/null +++ b/iotdb-core/ainode/tests/test_serving_optimization.py @@ -0,0 +1,234 @@ +# 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 pickle +import queue +import threading +import unittest +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import numpy as np +import pandas as pd +import test_inference_inputs as input_tests +import torch + +from iotdb.ainode.core.inference.batcher.bounded_request_batcher import ( + BoundedRequestBatcher, +) +from iotdb.ainode.core.inference.inference_request import ( + InferenceRequest, + InferenceResult, +) + + +class ServingOptimizationTest(unittest.TestCase): + def test_sdk_bulk_timestamps_match_scalar_conversion(self): + from iotdb.utils.iotdb_rpc_dataset import _timestamp_column_to_series + from iotdb.utils.rpc_utils import convert_to_timestamp + + for precision in ("ms", "us", "ns"): + for timezone in ("UTC", "Asia/Shanghai", "America/New_York"): + for endian in ("i8"): + with self.subTest( + precision=precision, timezone=timezone, endian=endian + ): + values = np.array([-1, 0, 1457848800000], dtype=endian) + actual = _timestamp_column_to_series( + values, precision, timezone + ) + expected = pd.Series( + [ + convert_to_timestamp(int(v), precision, timezone) + for v in values + ], + dtype=object, + ) + pd.testing.assert_series_equal(actual, expected) + + def test_sdk_bulk_timestamps_handle_empty_and_wide_dates(self): + from iotdb.utils.iotdb_rpc_dataset import _timestamp_column_to_series + from iotdb.utils.rpc_utils import convert_to_timestamp + + self.assertEqual( + len(_timestamp_column_to_series(np.array([], dtype="i8"), "ms", "UTC")), 0 + ) + values = np.array([32503680000000], dtype="i8") + actual = _timestamp_column_to_series(values, "ms", "UTC") + expected = pd.Series( + [convert_to_timestamp(int(values[0]), "ms", "UTC")], dtype=object + ) + pd.testing.assert_series_equal(actual, expected) + + def test_result_packet_has_no_request_inputs_or_torch_storage(self): + req = InferenceRequest( + "packet", "chronos2", inputs=torch.ones(1, 1, 4), output_length=2 + ) + req.write_step_output(torch.tensor([[[3.0, 4.0]]])) + packet = InferenceResult.from_request(req) + self.assertIsInstance(packet.output, np.ndarray) + self.assertEqual(set(vars(packet)), {"req_id", "output", "error"}) + restored = pickle.loads(pickle.dumps(packet)) + torch.testing.assert_close( + restored.get_final_output(), torch.tensor([[[3.0, 4.0]]]) + ) + req.output_tensor.zero_() + torch.testing.assert_close( + restored.get_final_output(), torch.tensor([[[3.0, 4.0]]]) + ) + + def test_failed_result_has_no_output_payload(self): + req = InferenceRequest( + "bad", "chronos2", inputs=torch.ones(1, 1, 4), output_length=2 + ) + req.mark_failed("input error") + packet = InferenceResult.from_request(req) + self.assertEqual(packet.error, "input error") + self.assertIsNone(packet.output) + + def request(self, name, value=1.0): + return InferenceRequest( + name, + "chronos2", + inputs=torch.full((1, 2, 4), value), + output_length=2, + ) + + def test_independent_multitarget_requests_share_one_forward(self): + reqs = [self.request("a", 1.0), self.request("b", 10.0)] + pool = input_tests.InferenceInputsTest().pool(reqs) + pool._step() + self.assertEqual(len(pool._inference_pipeline.calls), 1) + results = [pool._finished_queue.get_nowait() for _ in reqs] + torch.testing.assert_close( + results[0].get_final_output(), torch.full((1, 2, 2), 1.0) + ) + torch.testing.assert_close( + results[1].get_final_output(), torch.full((1, 2, 2), 10.0) + ) + + def test_plain_joint_requests_keep_their_own_input_groups(self): + reqs = [ + InferenceRequest( + name, + "chronos2", + inputs=torch.ones(1, 4), + output_length=2, + inference_attrs={"predict_batches_jointly": True}, + ) + for name in ("a", "b") + ] + pool = input_tests.InferenceInputsTest().pool(reqs) + pool._step() + self.assertEqual(len(pool._inference_pipeline.calls), 2) + + def test_rpc_boolean_options_reach_inference_as_booleans(self): + from iotdb.ainode.core.manager.inference_manager import InferenceManager + from iotdb.thrift.ainode.ttypes import TForecastReq + + manager = InferenceManager.__new__(InferenceManager) + manager._admit = MagicMock(return_value=None) + manager._inflight_slots = MagicMock() + manager._model_manager = MagicMock() + manager._model_manager.is_model_registered.return_value = False + manager._execute_prepared = MagicMock(return_value=torch.zeros(1, 1, 2)) + module = "iotdb.ainode.core.manager.inference_manager" + with patch( + module + ".convert_tsblock_to_tensor", return_value=torch.ones(1, 1, 4) + ): + for value, expected in (("false", False), ("TRUE", True)): + with self.subTest(value=value): + response = manager.forecast( + TForecastReq( + modelId="chronos2", + inputData=b"", + outputLength=2, + options={"predict_batches_jointly": value}, + ) + ) + self.assertEqual(response.status.code, 200) + request = manager._execute_prepared.call_args.args[3]() + self.assertIs( + request.inference_attrs["predict_batches_jointly"], expected + ) + manager._execute_prepared.reset_mock() + response = manager.forecast( + TForecastReq( + modelId="chronos2", + inputData=b"", + outputLength=2, + options={"predict_batches_jointly": "invalid"}, + ) + ) + self.assertNotEqual(response.status.code, 200) + manager._execute_prepared.assert_not_called() + + def batcher(self, sizes, budget=5, limit=32): + q = queue.Queue() + for index, size in enumerate(sizes): + q.put( + SimpleNamespace( + req_id=index, model_inputs=[{"targets": torch.ones(1, size)}] + ) + ) + return BoundedRequestBatcher(q, threading.Event(), limit, budget) + + def test_continuations_alternate_with_new_requests(self): + batcher = self.batcher([1, 1, 1], limit=1) + continuation = SimpleNamespace(req_id="continuation", model_inputs=[]) + batcher.requeue(continuation) + self.assertEqual(batcher.schedule_step()[0].req_id, 0) + self.assertIs(batcher.schedule_step()[0], continuation) + self.assertEqual(batcher.schedule_step()[0].req_id, 1) + + def test_over_budget_first_request_is_admitted_without_memory_gate(self): + batcher = self.batcher([20, 2]) + with patch( + "torch.cuda.memory_allocated", + side_effect=AssertionError("must not gate on resident weights"), + ): + self.assertEqual([r.req_id for r in batcher.schedule_step()], [0]) + self.assertEqual([r.req_id for r in batcher.schedule_step()], [1]) + + def test_budget_overflow_preserves_fifo(self): + batcher = self.batcher([3, 3, 2]) + self.assertEqual([r.req_id for r in batcher.schedule_step()], [0]) + self.assertEqual([r.req_id for r in batcher.schedule_step()], [1, 2]) + + def test_batch_request_limit_is_enforced(self): + batcher = self.batcher([1, 1, 1], budget=20, limit=2) + self.assertEqual([r.req_id for r in batcher.schedule_step()], [0, 1]) + self.assertEqual([r.req_id for r in batcher.schedule_step()], [2]) + + def test_batch_budget_counts_all_targets(self): + self.assertEqual( + BoundedRequestBatcher._points(self.request("r").model_inputs), 8 + ) + + def test_batcher_stops_without_waiting(self): + batcher = self.batcher([]) + batcher.stop_event.set() + self.assertEqual(batcher.schedule_step(), []) + + def test_nonpositive_batch_budget_is_rejected(self): + with self.assertRaises(ValueError): + self.batcher([], budget=0) + + +if __name__ == "__main__": + unittest.main() diff --git a/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/process/function/TableFunctionOperator.java b/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/process/function/TableFunctionOperator.java index b7ce9464259f9..e2fcb31460881 100644 --- a/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/process/function/TableFunctionOperator.java +++ b/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/process/function/TableFunctionOperator.java @@ -29,11 +29,13 @@ import org.apache.iotdb.calc.i18n.CalcMessages; import org.apache.iotdb.calc.plan.planner.CommonOperatorUtils; import org.apache.iotdb.commons.queryengine.execution.MemoryEstimationHelper; +import org.apache.iotdb.commons.queryengine.plan.relational.function.AsyncTableFunctionDataProcessor; import org.apache.iotdb.udf.api.IoTDBLocal; import org.apache.iotdb.udf.api.relational.access.Record; import org.apache.iotdb.udf.api.relational.table.TableFunctionProcessorProvider; import org.apache.iotdb.udf.api.relational.table.processor.TableFunctionDataProcessor; +import org.apache.ratis.thirdparty.com.google.common.util.concurrent.Futures; import org.apache.ratis.thirdparty.com.google.common.util.concurrent.ListenableFuture; import org.apache.tsfile.block.column.Column; import org.apache.tsfile.block.column.ColumnBuilder; @@ -72,11 +74,14 @@ public class TableFunctionOperator extends AbstractOperator implements ProcessOp private final boolean requireRecordSnapshot; private final boolean isDeclaredAsPassThrough; private final IoTDBLocal ioTDBLocal; + private final long queryDeadlineMillis; private TableFunctionDataProcessor processor; private PartitionState partitionState; private ListenableFuture isBlocked; private boolean finished = false; + private ListenableFuture finishFuture; + private ColumnBuilder finishPassThroughIndexBuilder; private final Queue resultTsBlocks; @@ -92,7 +97,8 @@ public TableFunctionOperator( boolean isDeclaredAsPassThrough, List partitionChannels, boolean requireRecordSnapshot, - IoTDBLocal ioTDBLocal) { + IoTDBLocal ioTDBLocal, + long queryDeadlineMillis) { checkArgument( ioTDBLocal != null, CalcMessages.EXCEPTION_IOTDBLOCAL_MUST_NOT_BE_NULL_FOR_TABLE_FUNCTION_5580D0A5); @@ -111,10 +117,14 @@ public TableFunctionOperator( this.resultTsBlocks = new LinkedList<>(); this.requireRecordSnapshot = requireRecordSnapshot; this.ioTDBLocal = ioTDBLocal; + this.queryDeadlineMillis = queryDeadlineMillis; } @Override public ListenableFuture isBlocked() { + if (finishFuture != null) { + return finishFuture; + } if (isBlocked == null) { isBlocked = tryGetNextTsBlock(); } @@ -156,10 +166,13 @@ public TsBlock next() throws Exception { return null; } else { List properColumnBuilders = getProperColumnBuilders(); - ColumnBuilder passThroughIndexBuilder = getPassThroughIndexBuilder(); + ColumnBuilder passThroughIndexBuilder = + finishFuture == null ? getPassThroughIndexBuilder() : finishPassThroughIndexBuilder; if (stateType == PartitionState.StateType.FINISHED) { if (processor != null) { - processor.finish(properColumnBuilders, passThroughIndexBuilder, ioTDBLocal); + if (!finishProcessor(properColumnBuilders, passThroughIndexBuilder)) { + return null; + } } finished = true; resultTsBlocks.addAll(buildTsBlock(properColumnBuilders, passThroughIndexBuilder)); @@ -170,7 +183,9 @@ public TsBlock next() throws Exception { if (stateType == PartitionState.StateType.NEW_PARTITION) { if (processor != null) { // previous partition state has not finished consuming yet - processor.finish(properColumnBuilders, passThroughIndexBuilder, ioTDBLocal); + if (!finishProcessor(properColumnBuilders, passThroughIndexBuilder)) { + return null; + } resultTsBlocks.addAll(buildTsBlock(properColumnBuilders, passThroughIndexBuilder)); partitionCache.clear(); destroyProcessor(processor); @@ -181,10 +196,8 @@ public TsBlock next() throws Exception { processor.beforeStart(ioTDBLocal); } } - // the cached slices are only needed when the output has - // columns declared as pass-through. Without them every output column is written by the - // processor, so the input block should not be retained in the partitionCache - if (needPassThrough) { + if (needPassThrough + && (isDeclaredAsPassThrough || stateType == PartitionState.StateType.NEW_PARTITION)) { partitionCache.addSlice(slice); } Iterator recordIterator = slice.getRequiredRecordIterator(requireRecordSnapshot); @@ -211,6 +224,26 @@ private TsBlock getNextResultTsBlock() { return resultTsBlock == null ? null : checkTsBlockSizeAndGetResult(); } + private boolean finishProcessor( + List builders, ColumnBuilder passThroughIndexBuilder) throws Exception { + if (!(processor instanceof AsyncTableFunctionDataProcessor asyncProcessor)) { + processor.finish(builders, passThroughIndexBuilder, ioTDBLocal); + return true; + } + if (finishFuture == null) { + asyncProcessor.setQueryDeadline(queryDeadlineMillis); + finishPassThroughIndexBuilder = passThroughIndexBuilder; + finishFuture = asyncProcessor.finishAsync(builders, passThroughIndexBuilder); + } + if (!finishFuture.isDone()) { + return false; + } + Futures.getDone(finishFuture); + finishFuture = null; + finishPassThroughIndexBuilder = null; + return true; + } + private List getProperColumnBuilders() { return Arrays.asList(properBlockBuilder.getValueColumnBuilders()); } @@ -280,16 +313,26 @@ public boolean hasNext() throws Exception { @Override public void close() throws Exception { + if (finishFuture != null) { + finishFuture.cancel(true); + finishPassThroughIndexBuilder = null; + } partitionCache.close(); resultTsBlocks.clear(); resultTsBlock = null; retainedTsBlock = null; - inputOperator.close(); - if (processor != null) { - destroyProcessor(processor); - processor = null; + try { + inputOperator.close(); + } finally { + try { + if (processor != null) { + destroyProcessor(processor); + processor = null; + } + } finally { + ioTDBLocal.close(); + } } - ioTDBLocal.close(); } @Override diff --git a/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/plan/planner/TableOperatorGenerator.java b/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/plan/planner/TableOperatorGenerator.java index c7e9a7f600ba9..b7849a548d33b 100644 --- a/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/plan/planner/TableOperatorGenerator.java +++ b/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/plan/planner/TableOperatorGenerator.java @@ -1695,7 +1695,8 @@ public Operator visitTableFunctionProcessor(TableFunctionProcessorNode node, C c .orElse(false), partitionChannels, node.isRequireRecordSnapshot(), - ioTDBLocal); + ioTDBLocal, + getOuterQueryDeadlineMs(context)); } } diff --git a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java index 5a75dd7bb38cf..562868e0d6b6e 100644 --- a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java +++ b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java @@ -21,7 +21,14 @@ /** Compile-time i18n constants for DataNode misc subsystems (English). */ public final class DataNodeMiscMessages { - public static final String EXCEPTION_INVALID_IOTCONSENSUS_LOG_COMPRESSION_CODEC_ARG_2B9C27F7 = "Invalid IoTConsensus log compression codec: %s"; + public static final String EXCEPTION_DN_AINODE_MAX_INPUT_LENGTH_MUST_BE_POSITIVE_GOT_ARG_6A764525 = + "dn_ainode_max_input_length must be positive, got %d"; + public static final String + EXCEPTION_INFERENCE_QUERY_DEADLINE_EXCEEDED_OR_QUERY_WAS_CANCELLED_8AA7D05C = + "Inference query deadline exceeded or query was cancelled"; + public static final String EXCEPTION_INVALID_IOTCONSENSUS_LOG_COMPRESSION_CODEC_ARG_2B9C27F7 = + "Invalid IoTConsensus log compression codec: %s"; + public static final String LOG_FAILED_TO_AUTHORIZE_CQ_ARG_FOR_USER_ARG_ARG_B436A81F = "Failed to authorize CQ {} for user {}: {}"; diff --git a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java index 485a32e7448d0..89389b9d9dcfa 100644 --- a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java +++ b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java @@ -21,7 +21,14 @@ /** 编译时国际化常量 - DataNode 杂项子系统(中文)。 */ public final class DataNodeMiscMessages { - public static final String EXCEPTION_INVALID_IOTCONSENSUS_LOG_COMPRESSION_CODEC_ARG_2B9C27F7 = "无效的 IoTConsensus 日志压缩算法:%s"; + public static final String EXCEPTION_DN_AINODE_MAX_INPUT_LENGTH_MUST_BE_POSITIVE_GOT_ARG_6A764525 = + "dn_ainode_max_input_length 必须为正数,实际为 %d"; + public static final String + EXCEPTION_INFERENCE_QUERY_DEADLINE_EXCEEDED_OR_QUERY_WAS_CANCELLED_8AA7D05C = + "推理查询超时或已取消"; + public static final String EXCEPTION_INVALID_IOTCONSENSUS_LOG_COMPRESSION_CODEC_ARG_2B9C27F7 = + "无效的 IoTConsensus 日志压缩算法:%s"; + public static final String LOG_FAILED_TO_AUTHORIZE_CQ_ARG_FOR_USER_ARG_ARG_B436A81F = "CQ {} 的用户 {} 鉴权失败:{}"; diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java index bd2895f887642..970e546d359ef 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java @@ -28,6 +28,7 @@ import org.apache.iotdb.commons.enums.ReadConsistencyLevel; import org.apache.iotdb.commons.i18n.CommonMessages; import org.apache.iotdb.commons.pipe.config.PipeConfig; +import org.apache.iotdb.commons.queryengine.plan.relational.function.ITableFunctionAINodeService; import org.apache.iotdb.commons.utils.FileUtils; import org.apache.iotdb.consensus.ConsensusFactory; import org.apache.iotdb.db.exception.LoadConfigurationException; @@ -628,6 +629,10 @@ public class IoTDBConfig implements DefaultEncodingProvider { /** the max executing time of query in ms. Unit: millisecond */ private long queryTimeoutThreshold = 60000; + static final String AINODE_MAX_INPUT_LENGTH_PROPERTY = "dn_ainode_max_input_length"; + + private int ainodeMaxInputLength = ITableFunctionAINodeService.DEFAULT_MAX_INPUT_LENGTH; + /** the max time to live of a session in ms. Unit: millisecond */ private int sessionTimeoutThreshold = 0; @@ -2135,6 +2140,21 @@ public void setQueryTimeoutThreshold(long queryTimeoutThreshold) { this.queryTimeoutThreshold = queryTimeoutThreshold; } + public int getAINodeMaxInputLength() { + return ainodeMaxInputLength; + } + + public void setAINodeMaxInputLength(int ainodeMaxInputLength) { + if (ainodeMaxInputLength <= 0) { + throw new IllegalArgumentException( + String.format( + DataNodeMiscMessages + .EXCEPTION_DN_AINODE_MAX_INPUT_LENGTH_MUST_BE_POSITIVE_GOT_ARG_6A764525, + ainodeMaxInputLength)); + } + this.ainodeMaxInputLength = ainodeMaxInputLength; + } + public int getSessionTimeoutThreshold() { return sessionTimeoutThreshold; } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java index 4eec35ca33d5c..d32a3cf99ffcf 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java @@ -273,6 +273,7 @@ private boolean loadProps() { } public void loadProperties(TrimProperties properties) throws BadNodeUrlException, IOException { + loadAINodeInputProperties(properties); ConfigurationFileUtils.updateAppliedProperties(properties, false); conf.setClusterName(properties.getProperty(IoTDBConstant.CLUSTER_NAME, conf.getClusterName())); @@ -2906,6 +2907,14 @@ private void loadPipeHotModifiedProp(TrimProperties properties) throws IOExcepti LoggerPeriodicalLogReducer.update(); } + void loadAINodeInputProperties(TrimProperties properties) { + conf.setAINodeMaxInputLength( + Integer.parseInt( + properties.getProperty( + IoTDBConfig.AINODE_MAX_INPUT_LENGTH_PROPERTY, + Integer.toString(conf.getAINodeMaxInputLength())))); + } + @SuppressWarnings("squid:S3518") // "proportionSum" can't be zero private void loadUDFProps(TrimProperties properties) { String initialByteArrayLengthForMemoryControl = diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/client/an/AINodeClient.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/client/an/AINodeClient.java index 626f86fd8c656..c59668d42ad96 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/client/an/AINodeClient.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/client/an/AINodeClient.java @@ -57,6 +57,7 @@ import org.apache.iotdb.db.protocol.client.ConfigNodeClientManager; import org.apache.iotdb.db.protocol.client.ConfigNodeInfo; import org.apache.iotdb.rpc.DeepCopyRpcTransportFactory; +import org.apache.iotdb.rpc.TimeoutChangeableTransport; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; @@ -73,6 +74,8 @@ public class AINodeClient implements IAINodeRPCService.Iface, AutoCloseable, ThriftClient { + static final String INFERENCE_TIMEOUT_OPTION = "_ain_timeout_ms"; + private static final Logger LOGGER = LoggerFactory.getLogger(AINodeClient.class); private static final CommonConfig COMMON_CONFIG = CommonDescriptor.getInstance().getConfig(); @@ -148,16 +151,59 @@ public TSStatus unloadModel(TUnloadModelReq req) throws TException { @Override public TInferenceResp inference(TInferenceReq req) throws TException { - return executeRemoteCallWithRetry(() -> client.inference(req)); + return executeInferenceCall( + () -> client.inference(req), + transport, + property.getConnectionTimeoutMs(), + property.getConnectionTimeoutMs()); } @Override public TForecastResp forecast(TForecastReq req) throws TException { - return executeRemoteCallWithRetry(() -> client.forecast(req)); + int timeout = property.getConnectionTimeoutMs(); + if (req.getOptions() != null && req.getOptions().containsKey(INFERENCE_TIMEOUT_OPTION)) { + timeout = + (int) + Math.max( + 0, + Math.min( + Integer.MAX_VALUE, + Long.parseLong(req.getOptions().get(INFERENCE_TIMEOUT_OPTION)))); + } + return executeInferenceCall( + () -> client.forecast(req), transport, timeout, property.getConnectionTimeoutMs()); + } + + // A transport failure does not tell us whether inference has executed. + // Replaying it can multiply load while the original call is still running. + static R executeInferenceCall( + RemoteCall call, TTransport transport, int timeout, int defaultTimeout) throws TException { + if (timeout <= 0 || Thread.currentThread().isInterrupted()) { + throw new TException( + DataNodeMiscMessages + .EXCEPTION_INFERENCE_QUERY_DEADLINE_EXCEEDED_OR_QUERY_WAS_CANCELLED_8AA7D05C); + } + TimeoutChangeableTransport timedTransport = + transport instanceof TimeoutChangeableTransport + ? (TimeoutChangeableTransport) transport + : null; + try { + if (timedTransport != null) { + timedTransport.setTimeout(timeout); + } + return call.apply(); + } catch (TException e) { + transport.close(); + throw e; + } finally { + if (timedTransport != null && transport.isOpen()) { + timedTransport.setTimeout(defaultTimeout); + } + } } @FunctionalInterface - private interface RemoteCall { + interface RemoteCall { R apply() throws TException; } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/client/an/DataNodeTableFunctionAINodeService.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/client/an/DataNodeTableFunctionAINodeService.java index bd442a14d8a86..c0329a4a59bbe 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/client/an/DataNodeTableFunctionAINodeService.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/client/an/DataNodeTableFunctionAINodeService.java @@ -24,10 +24,15 @@ import org.apache.iotdb.commons.client.IClientManager; import org.apache.iotdb.commons.client.exception.ClientManagerException; import org.apache.iotdb.commons.queryengine.plan.relational.function.ITableFunctionAINodeService; +import org.apache.iotdb.db.conf.IoTDBDescriptor; import org.apache.iotdb.db.exception.ainode.AINodeConnectionException; +import org.apache.iotdb.db.i18n.DataNodeMiscMessages; import org.apache.thrift.TException; +import java.util.HashMap; +import java.util.Map; + public class DataNodeTableFunctionAINodeService implements ITableFunctionAINodeService { private static final IClientManager CLIENT_MANAGER = @@ -38,6 +43,11 @@ public class DataNodeTableFunctionAINodeService implements ITableFunctionAINodeS private DataNodeTableFunctionAINodeService() {} + @Override + public int getMaxInputLength() { + return IoTDBDescriptor.getInstance().getConfig().getAINodeMaxInputLength(); + } + @Override public TForecastResp forecast(TForecastReq req) { try (AINodeClient client = @@ -47,4 +57,48 @@ public TForecastResp forecast(TForecastReq req) { throw new AINodeConnectionException(e); } } + + @Override + public TForecastResp forecast( + TForecastReq req, long deadlineMillis, ForecastCancellation cancellation) { + try { + remainingTimeoutMillis(deadlineMillis, cancellation); + try (AINodeClient client = + CLIENT_MANAGER.borrowClient(AINodeClientManager.AINODE_ID_PLACEHOLDER)) { + if (!cancellation.register(client::invalidate)) { + throw inferenceCancelled(); + } + try { + long remainingMillis = remainingTimeoutMillis(deadlineMillis, cancellation); + if (deadlineMillis > 0) { + Map options = + req.isSetOptions() ? new HashMap<>(req.getOptions()) : new HashMap<>(); + options.put(AINodeClient.INFERENCE_TIMEOUT_OPTION, Long.toString(remainingMillis)); + req.setOptions(options); + } + return client.forecast(req); + } finally { + cancellation.unregister(); + } + } + } catch (ClientManagerException | TException e) { + throw new AINodeConnectionException(e); + } + } + + private static long remainingTimeoutMillis(long deadlineMillis, ForecastCancellation cancellation) + throws TException { + long remaining = + deadlineMillis > 0 ? deadlineMillis - System.currentTimeMillis() : Long.MAX_VALUE; + if (remaining <= 0 || cancellation.isCancelled() || Thread.currentThread().isInterrupted()) { + throw inferenceCancelled(); + } + return remaining; + } + + private static TException inferenceCancelled() { + return new TException( + DataNodeMiscMessages + .EXCEPTION_INFERENCE_QUERY_DEADLINE_EXCEEDED_OR_QUERY_WAS_CANCELLED_8AA7D05C); + } } diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/commons/queryengine/plan/relational/function/tvf/AINodeInputWindowTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/commons/queryengine/plan/relational/function/tvf/AINodeInputWindowTest.java new file mode 100644 index 0000000000000..067176993df39 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/commons/queryengine/plan/relational/function/tvf/AINodeInputWindowTest.java @@ -0,0 +1,454 @@ +/* + * 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. + */ + +package org.apache.iotdb.commons.queryengine.plan.relational.function.tvf; + +import org.apache.iotdb.ainode.rpc.thrift.TForecastReq; +import org.apache.iotdb.ainode.rpc.thrift.TForecastResp; +import org.apache.iotdb.calc.execution.operator.process.function.partition.Slice; +import org.apache.iotdb.common.rpc.thrift.TSStatus; +import org.apache.iotdb.commons.exception.IoTDBRuntimeException; +import org.apache.iotdb.commons.queryengine.plan.relational.function.tvf.ClassifyTableFunction.ClassifyDataProcessor; +import org.apache.iotdb.commons.queryengine.plan.relational.function.tvf.ClassifyTableFunction.ClassifyTableFunctionHandle; +import org.apache.iotdb.commons.queryengine.plan.relational.function.tvf.ForecastTableFunction.ForecastDataProcessor; +import org.apache.iotdb.commons.queryengine.plan.relational.function.tvf.ForecastTableFunction.ForecastTableFunctionHandle; +import org.apache.iotdb.commons.queryengine.plan.udf.UDTFForecast; +import org.apache.iotdb.db.conf.IoTDBConfig; +import org.apache.iotdb.db.conf.IoTDBDescriptor; +import org.apache.iotdb.rpc.TSStatusCode; +import org.apache.iotdb.udf.api.collector.PointCollector; +import org.apache.iotdb.udf.api.customizer.config.UDTFConfigurations; +import org.apache.iotdb.udf.api.customizer.parameter.UDFParameters; +import org.apache.iotdb.udf.api.relational.access.Record; +import org.apache.iotdb.udf.api.relational.table.TableFunctionAnalysis; +import org.apache.iotdb.udf.api.relational.table.argument.Argument; +import org.apache.iotdb.udf.api.relational.table.argument.ScalarArgument; +import org.apache.iotdb.udf.api.relational.table.argument.TableArgument; +import org.apache.iotdb.udf.api.relational.table.processor.TableFunctionDataProcessor; +import org.apache.iotdb.udf.api.type.Type; +import org.apache.iotdb.udf.api.utils.RowImpl; + +import org.apache.tsfile.block.column.Column; +import org.apache.tsfile.block.column.ColumnBuilder; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.read.common.block.TsBlock; +import org.apache.tsfile.read.common.block.TsBlockBuilder; +import org.apache.tsfile.read.common.block.column.TsBlockSerde; +import org.junit.After; +import org.junit.Test; +import org.mockito.InOrder; + +import java.io.IOException; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Random; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class AINodeInputWindowTest { + private static final TsBlockSerde SERDE = new TsBlockSerde(); + private static final List TABLE_TYPES = Arrays.asList(Type.TIMESTAMP, Type.DOUBLE); + private static final List TABLE_STORAGE_TYPES = + Arrays.asList(TSDataType.TIMESTAMP, TSDataType.DOUBLE); + private static final TSDataType[] TREE_STORAGE_TYPES = {TSDataType.DOUBLE, TSDataType.INT64}; + private static final String MODEL = "window-test"; + private static final double FORECAST_VALUE = 42; + private final IoTDBConfig config = IoTDBDescriptor.getInstance().getConfig(); + private final int previousLimit = config.getAINodeMaxInputLength(); + + @After + public void restoreInputLimit() { + config.setAINodeMaxInputLength(previousLimit); + } + + @Test + public void testClassifyHandleRoundTripPreservesColumnTypes() { + ClassifyTableFunctionHandle original = + new ClassifyTableFunctionHandle( + MODEL, 8192, Arrays.asList(Type.INT32, Type.INT64, Type.FLOAT, Type.DOUBLE)); + ClassifyTableFunctionHandle restored = new ClassifyTableFunctionHandle(); + + restored.deserialize(original.serialize()); + + assertEquals(original, restored); + } + + @Test + public void testTableForecastSerializesMultipleTargetsInSchemaOrder() { + RequestRecorder rpc = new RequestRecorder(false); + Map arguments = forecastArguments(false, 1); + arguments.put( + "TARGETS", + new TableArgument( + Arrays.asList(Optional.of("time"), Optional.of("first"), Optional.of("second")), + Arrays.asList(Type.TIMESTAMP, Type.DOUBLE, Type.INT32), + Collections.emptyList(), + Collections.emptyList(), + false)); + ForecastDataProcessor forecast = forecastProcessor(arguments, rpc); + Record record = mock(Record.class); + when(record.getLong(0)).thenReturn(5L); + when(record.getDouble(1)).thenReturn(1.25); + when(record.getInt(2)).thenReturn(9); + List output = + builders(TSDataType.TIMESTAMP, TSDataType.DOUBLE, TSDataType.INT32); + + forecast.process(record, output, null); + forecast.finish(output, null); + + assertEquals(5L, rpc.input.getTimeByIndex(0)); + assertEquals(2, rpc.input.getValueColumnCount()); + assertEquals(1.25, rpc.input.getColumn(0).getDouble(0), 0); + assertEquals(9.0, rpc.input.getColumn(1).getDouble(0), 0); + assertEquals(6L, output.get(0).build().getLong(0)); + assertEquals(42.0, output.get(1).build().getDouble(0), 0); + assertEquals(43, output.get(2).build().getInt(0)); + } + + @Test + public void testLatest2880RowsAcrossArrivalOrders() throws Exception { + config.setAINodeMaxInputLength(2880); + List ascending = new ArrayList<>(); + for (int time = 1; time <= 5760; time++) { + ascending.add(new Input((long) time, 10.0 * time)); + } + List expected = ascending.subList(2880, 5760); + List descending = new ArrayList<>(ascending); + Collections.reverse(descending); + List shuffled = new ArrayList<>(ascending); + Collections.shuffle(shuffled, new Random(47)); + + for (List input : Arrays.asList(ascending, descending, shuffled)) { + assertAllEntrypoints(input, expected, false, 0, 5761L); + } + } + + @Test + public void testCutoffTiesBoundaryAndShortInput() throws Exception { + config.setAINodeMaxInputLength(3); + Input latest = new Input(12L, 120.0); + Input firstTie = new Input(11L, 111.0); + Input middleTie = new Input(11L, 112.0); + Input lastTie = new Input(11L, 113.0); + + assertAllEntrypoints( + Arrays.asList(latest, firstTie, middleTie, new Input(10L, 100.0), lastTie), + Arrays.asList(middleTie, lastTie, latest), + true, + 1, + 13); + assertAllEntrypoints( + Arrays.asList(latest, firstTie, middleTie), + Arrays.asList(firstTie, middleTie, latest), + false, + 1, + 13); + assertAllEntrypoints( + Collections.singletonList(latest), Collections.singletonList(latest), false, 1, 13); + + config.setAINodeMaxInputLength(1); + assertAllEntrypoints( + Arrays.asList(latest, firstTie), Collections.singletonList(latest), true, 1, 13); + } + + @Test + public void testExistingNullHandling() throws Exception { + config.setAINodeMaxInputLength(2); + List rows = Arrays.asList(new Input(3L, null), new Input(null, 10.0)); + List selected = Arrays.asList(new Input(0L, 10.0), rows.get(0)); + + RequestRecorder forecastRpc = new RequestRecorder(false); + ForecastDataProcessor forecast = forecastProcessor(false, 1, forecastRpc); + List forecastOutput = forecastBuilders(false); + feedTable(forecast, rows, forecastOutput); + forecast.finish(forecastOutput, null); + assertWindow(selected, forecastRpc.input, Double.NaN); + + RequestRecorder classifyRpc = new RequestRecorder(true); + ClassifyDataProcessor classify = classifyProcessor(classifyRpc); + List classifyOutput = builders(TSDataType.TIMESTAMP, TSDataType.INT32); + feedTable(classify, rows, classifyOutput); + classify.finish(classifyOutput, null); + assertWindow(selected, classifyRpc.input, 0.0); + + ForecastDataProcessor preserveForecast = forecastProcessor(true, 1, new RequestRecorder(false)); + assertThrows( + IoTDBRuntimeException.class, + () -> feedTable(preserveForecast, rows, forecastBuilders(true))); + + RequestRecorder treeRpc = new RequestRecorder(false); + UDTFForecast tree = treeForecast(false, 1, treeRpc); + PointCollector collector = mock(PointCollector.class); + tree.transform(treeRow(rows.get(0)), collector); + tree.terminate(collector); + assertTrue(treeRpc.input.getColumn(0).isNull(0)); + } + + private void assertAllEntrypoints( + List arrivals, List selected, boolean preserve, long interval, long nextTime) + throws Exception { + RequestRecorder forecastRpc = new RequestRecorder(false); + ForecastDataProcessor forecast = forecastProcessor(preserve, interval, forecastRpc); + List forecastOutput = forecastBuilders(preserve); + feedTable(forecast, arrivals, forecastOutput); + forecast.finish(forecastOutput, null); + assertWindow(selected, forecastRpc.input, Double.NaN); + Column outputTimes = forecastOutput.get(0).build(); + Column outputValues = forecastOutput.get(1).build(); + int forecastRow = preserve ? arrivals.size() : 0; + assertEquals(forecastRow + 1, outputTimes.getPositionCount()); + assertEquals(nextTime, outputTimes.getLong(forecastRow)); + assertEquals(FORECAST_VALUE, outputValues.getDouble(forecastRow), 0.0); + if (preserve) { + Column isInput = forecastOutput.get(2).build(); + for (int index = 0; index < arrivals.size(); index++) { + Input arrival = arrivals.get(index); + assertEquals(arrival.time.longValue(), outputTimes.getLong(index)); + assertEquals(arrival.value, outputValues.getDouble(index), 0.0); + assertTrue(isInput.getBoolean(index)); + } + assertFalse(isInput.getBoolean(forecastRow)); + } + + RequestRecorder classifyRpc = new RequestRecorder(true); + ClassifyDataProcessor classify = classifyProcessor(classifyRpc); + List classifyOutput = builders(TSDataType.TIMESTAMP, TSDataType.INT32); + feedTable(classify, arrivals, classifyOutput); + classify.finish(classifyOutput, null); + assertWindow(selected, classifyRpc.input, 0); + Column categoryTimes = classifyOutput.get(0).build(); + Column categories = classifyOutput.get(1).build(); + assertEquals(selected.size(), categoryTimes.getPositionCount()); + assertEquals(selected.size(), categories.getPositionCount()); + for (int index = 0; index < selected.size(); index++) { + assertEquals(selected.get(index).time.longValue(), categoryTimes.getLong(index)); + assertEquals(selected.get(index).value.intValue(), categories.getInt(index)); + } + + RequestRecorder treeRpc = new RequestRecorder(false); + UDTFForecast tree = treeForecast(preserve, interval, treeRpc); + PointCollector collector = mock(PointCollector.class); + for (Input arrival : arrivals) { + tree.transform(treeRow(arrival), collector); + } + tree.terminate(collector); + assertWindow(selected, treeRpc.input, Double.NaN); + InOrder delivery = inOrder(collector); + if (preserve) { + for (Input arrival : arrivals) { + delivery.verify(collector).putDouble(arrival.time, arrival.value); + } + } + delivery.verify(collector).putDouble(nextTime, FORECAST_VALUE); + delivery.verifyNoMoreInteractions(); + } + + private static ForecastDataProcessor forecastProcessor( + boolean preserve, long interval, RequestRecorder rpc) { + return forecastProcessor(forecastArguments(preserve, interval), rpc); + } + + private static Map forecastArguments(boolean preserve, long interval) { + Map arguments = tableArguments("TARGETS"); + arguments.put("OUTPUT_LENGTH", new ScalarArgument(Type.INT32, 1)); + arguments.put("OUTPUT_START_TIME", new ScalarArgument(Type.TIMESTAMP, Long.MIN_VALUE)); + arguments.put("OUTPUT_INTERVAL", new ScalarArgument(Type.INT64, interval)); + arguments.put("PRESERVE_INPUT", new ScalarArgument(Type.BOOLEAN, preserve)); + arguments.put("MODEL_OPTIONS", new ScalarArgument(Type.STRING, "")); + return arguments; + } + + private static ForecastDataProcessor forecastProcessor( + Map arguments, RequestRecorder rpc) { + TableFunctionAnalysis analysis = new ForecastTableFunction().analyze(arguments); + ForecastTableFunctionHandle handle = new ForecastTableFunctionHandle(); + handle.deserialize(analysis.getTableFunctionHandle().serialize()); + return new ForecastDataProcessor(handle) { + @Override + TForecastResp invokeForecast(TForecastReq request) { + return rpc.reply(request); + } + }; + } + + private static ClassifyDataProcessor classifyProcessor(RequestRecorder rpc) throws Exception { + TableFunctionAnalysis analysis = new ClassifyTableFunction().analyze(tableArguments("INPUT")); + ClassifyTableFunctionHandle handle = new ClassifyTableFunctionHandle(); + handle.deserialize(analysis.getTableFunctionHandle().serialize()); + return new ClassifyDataProcessor(handle) { + @Override + TForecastResp invokeForecast(TForecastReq request) { + return rpc.reply(request); + } + }; + } + + private static UDTFForecast treeForecast(boolean preserve, long interval, RequestRecorder rpc) + throws Exception { + UDTFForecast tree = + new UDTFForecast() { + @Override + protected TForecastResp invokeForecast(TForecastReq request) { + return rpc.reply(request); + } + }; + Map attributes = new HashMap<>(); + attributes.put("MODEL_ID", MODEL); + attributes.put("OUTPUT_LENGTH", "1"); + attributes.put("OUTPUT_INTERVAL", Long.toString(interval)); + attributes.put("PRESERVE_INPUT", Boolean.toString(preserve)); + tree.beforeStart( + new UDFParameters( + Collections.singletonList("value"), Collections.singletonList(Type.DOUBLE), attributes), + new UDTFConfigurations(ZoneOffset.UTC)); + return tree; + } + + private static Map tableArguments(String tableParameter) { + Map arguments = new HashMap<>(); + arguments.put( + tableParameter, + new TableArgument( + Arrays.asList(Optional.of("time"), Optional.of("value")), + TABLE_TYPES, + Collections.emptyList(), + Collections.emptyList(), + false)); + arguments.put("MODEL_ID", new ScalarArgument(Type.STRING, MODEL)); + arguments.put("TIMECOL", new ScalarArgument(Type.STRING, "time")); + return arguments; + } + + private static void feedTable( + TableFunctionDataProcessor processor, List rows, List output) { + TsBlockBuilder source = new TsBlockBuilder(rows.size(), TABLE_STORAGE_TYPES); + for (Input row : rows) { + source.getTimeColumnBuilder().writeLong(0); + if (row.time == null) { + source.getColumnBuilder(0).appendNull(); + } else { + source.getColumnBuilder(0).writeLong(row.time); + } + if (row.value == null) { + source.getColumnBuilder(1).appendNull(); + } else { + source.getColumnBuilder(1).writeDouble(row.value); + } + source.declarePosition(); + } + Slice slice = + new Slice( + 0, + rows.size(), + source.build().getValueColumns(), + Arrays.asList(0, 1), + Collections.emptyList(), + TABLE_TYPES); + Iterator records = slice.getRequiredRecordIterator(false); + while (records.hasNext()) { + processor.process(records.next(), output, null); + } + } + + private static List forecastBuilders(boolean preserve) { + return preserve + ? builders(TSDataType.TIMESTAMP, TSDataType.DOUBLE, TSDataType.BOOLEAN) + : builders(TSDataType.TIMESTAMP, TSDataType.DOUBLE); + } + + private static List builders(TSDataType... types) { + return Arrays.asList(new TsBlockBuilder(Arrays.asList(types)).getValueColumnBuilders()); + } + + private static RowImpl treeRow(Input row) { + RowImpl input = new RowImpl(TREE_STORAGE_TYPES); + input.setRowRecord(new Object[] {row.value, row.time}); + return input; + } + + private static void assertWindow(List selected, TsBlock input, double nullValue) { + assertEquals(selected.size(), input.getPositionCount()); + assertEquals(1, input.getValueColumnCount()); + for (int index = 0; index < selected.size(); index++) { + Input expected = selected.get(index); + assertEquals(expected.time.longValue(), input.getTimeByIndex(index)); + assertEquals( + expected.value == null ? nullValue : expected.value, + input.getColumn(0).getDouble(index), + 0); + } + } + + private static final class Input { + private final Long time; + private final Double value; + + private Input(Long time, Double value) { + this.time = time; + this.value = value; + } + } + + private static final class RequestRecorder { + private final boolean classify; + private TsBlock input; + + private RequestRecorder(boolean classify) { + this.classify = classify; + } + + private TForecastResp reply(TForecastReq request) { + input = SERDE.deserialize(request.bufferForInputData()); + int expectedLength = classify ? input.getPositionCount() : 1; + assertEquals(expectedLength, request.getOutputLength()); + int columnCount = classify ? 1 : input.getValueColumnCount(); + TsBlockBuilder response = + new TsBlockBuilder(Collections.nCopies(columnCount, TSDataType.DOUBLE)); + for (int index = 0; index < expectedLength; index++) { + response.getTimeColumnBuilder().writeLong(index); + for (int column = 0; column < columnCount; column++) { + response + .getColumnBuilder(column) + .writeDouble( + classify ? input.getColumn(0).getDouble(index) : FORECAST_VALUE + column); + } + response.declarePosition(); + } + try { + return new TForecastResp(new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode())) + .setForecastResult(Collections.singletonList(SERDE.serialize(response.build()))); + } catch (IOException exception) { + throw new AssertionError(exception); + } + } + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/conf/IoTDBDescriptorTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/conf/IoTDBDescriptorTest.java index 5e0759c67313f..d77b268d0506b 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/conf/IoTDBDescriptorTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/conf/IoTDBDescriptorTest.java @@ -19,6 +19,7 @@ package org.apache.iotdb.db.conf; import org.apache.iotdb.commons.conf.IoTDBConstant; +import org.apache.iotdb.commons.conf.TrimProperties; import org.junit.After; import org.junit.Assert; @@ -90,6 +91,34 @@ public void testConfigURLWithPlainFilePath() { Assert.assertEquals(confURL.toString(), path.toString()); } + @Test + public void testAINodeInputLengthProperty() { + IoTDBDescriptor descriptor = IoTDBDescriptor.getInstance(); + IoTDBConfig config = descriptor.getConfig(); + int previous = config.getAINodeMaxInputLength(); + TrimProperties properties = new TrimProperties(); + String key = "dn_ainode_max_input_length"; + try { + Assert.assertEquals(2880, new IoTDBConfig().getAINodeMaxInputLength()); + config.setAINodeMaxInputLength(2880); + descriptor.loadAINodeInputProperties(properties); + Assert.assertEquals(2880, config.getAINodeMaxInputLength()); + + properties.setProperty(key, "8192"); + descriptor.loadAINodeInputProperties(properties); + Assert.assertEquals(8192, config.getAINodeMaxInputLength()); + + for (String value : new String[] {"0", "-2", "1.5"}) { + properties.setProperty(key, value); + Assert.assertThrows( + IllegalArgumentException.class, () -> descriptor.loadAINodeInputProperties(properties)); + Assert.assertEquals(8192, config.getAINodeMaxInputLength()); + } + } finally { + config.setAINodeMaxInputLength(previous); + } + } + static class ConfigurableStreamHandlerFactory implements URLStreamHandlerFactory { private final Map protocolHandlers; diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/protocol/client/an/AINodeInferenceCallTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/protocol/client/an/AINodeInferenceCallTest.java new file mode 100644 index 0000000000000..9b3df956fcb06 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/protocol/client/an/AINodeInferenceCallTest.java @@ -0,0 +1,133 @@ +/* + * 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. + */ + +package org.apache.iotdb.db.protocol.client.an; + +import org.apache.iotdb.commons.queryengine.plan.relational.function.ITableFunctionAINodeService.ForecastCancellation; +import org.apache.iotdb.rpc.TimeoutChangeableTransport; + +import org.apache.thrift.TException; +import org.apache.thrift.transport.TMemoryBuffer; +import org.junit.Test; + +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class AINodeInferenceCallTest { + private static class TimedTransport extends TMemoryBuffer implements TimeoutChangeableTransport { + int timeout = 1000; + boolean open = true; + + TimedTransport() throws Exception { + super(256); + } + + @Override + public void setTimeout(int value) { + timeout = value; + } + + @Override + public int getTimeOut() { + return timeout; + } + + @Override + public boolean isOpen() { + return open; + } + + @Override + public void close() { + open = false; + } + } + + @Test + public void doesNotReplayFailedInference() throws Exception { + TimedTransport transport = new TimedTransport(); + AtomicInteger calls = new AtomicInteger(); + try { + AINodeClient.executeInferenceCall( + () -> { + calls.incrementAndGet(); + throw new TException("reply lost after execution"); + }, + transport, + 50, + 1000); + fail("Expected transport failure"); + } catch (TException expected) { + assertEquals(1, calls.get()); + assertFalse(transport.isOpen()); + } + } + + @Test + public void restoresPooledConnectionTimeoutAfterSuccess() throws Exception { + TimedTransport transport = new TimedTransport(); + int result = + AINodeClient.executeInferenceCall( + () -> { + assertEquals(50, transport.getTimeOut()); + return 7; + }, + transport, + 50, + 1000); + assertEquals(7, result); + assertEquals(1000, transport.getTimeOut()); + } + + @Test + public void cancellationDoesNotSendInference() throws Exception { + TimedTransport transport = new TimedTransport(); + AtomicInteger calls = new AtomicInteger(); + Thread.currentThread().interrupt(); + try { + AINodeClient.executeInferenceCall(() -> calls.incrementAndGet(), transport, 50, 1000); + fail("Expected cancellation"); + } catch (TException expected) { + assertEquals(0, calls.get()); + } finally { + Thread.interrupted(); + } + } + + @Test + public void cancellationOnlyClosesTransportWhileItIsBorrowed() throws Exception { + TimedTransport inFlight = new TimedTransport(); + ForecastCancellation running = new ForecastCancellation(); + assertTrue(running.register(inFlight::close)); + running.cancel(); + assertFalse(inFlight.isOpen()); + assertFalse(running.register(inFlight::close)); + + TimedTransport reusable = new TimedTransport(); + ForecastCancellation completed = new ForecastCancellation(); + assertTrue(completed.register(reusable::close)); + completed.unregister(); + completed.cancel(); + assertTrue(reusable.isOpen()); + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/function/TableFunctionAsyncFinishTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/function/TableFunctionAsyncFinishTest.java new file mode 100644 index 0000000000000..076fb0d1bcf62 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/function/TableFunctionAsyncFinishTest.java @@ -0,0 +1,166 @@ +/* + * 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. + */ + +package org.apache.iotdb.db.queryengine.execution.operator.process.function; + +import org.apache.iotdb.calc.execution.operator.Operator; +import org.apache.iotdb.calc.execution.operator.process.function.TableFunctionOperator; +import org.apache.iotdb.commons.queryengine.plan.relational.function.AsyncTableFunctionDataProcessor; +import org.apache.iotdb.udf.api.IoTDBLocal; +import org.apache.iotdb.udf.api.relational.access.Record; +import org.apache.iotdb.udf.api.relational.table.processor.TableFunctionDataProcessor; + +import org.apache.ratis.thirdparty.com.google.common.util.concurrent.ListenableFuture; +import org.apache.ratis.thirdparty.com.google.common.util.concurrent.SettableFuture; +import org.apache.tsfile.block.column.ColumnBuilder; +import org.apache.tsfile.enums.TSDataType; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ExecutionException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class TableFunctionAsyncFinishTest { + private static final long QUERY_DEADLINE_MILLIS = 1234567L; + private final IoTDBLocal local = mock(IoTDBLocal.class); + + private static class Processor implements AsyncTableFunctionDataProcessor { + final SettableFuture future = SettableFuture.create(); + int submissions; + boolean destroyed; + long deadlineMillis; + + @Override + public void process(Record record, List builders, ColumnBuilder index) {} + + @Override + public void setQueryDeadline(long deadlineMillis) { + this.deadlineMillis = deadlineMillis; + } + + @Override + public ListenableFuture finishAsync(List builders, ColumnBuilder index) { + submissions++; + return future; + } + + @Override + public void beforeDestroy() { + destroyed = true; + } + } + + private TableFunctionOperator operator(TableFunctionDataProcessor processor) throws Exception { + TableFunctionOperator operator = + new TableFunctionOperator( + null, + null, + mock(Operator.class), + Collections.emptyList(), + Collections.singletonList(TSDataType.DOUBLE), + 1, + Collections.emptyList(), + Collections.emptyList(), + false, + Collections.emptyList(), + false, + local, + QUERY_DEADLINE_MILLIS); + Field field = TableFunctionOperator.class.getDeclaredField("processor"); + field.setAccessible(true); + field.set(operator, processor); + return operator; + } + + private boolean finish(TableFunctionOperator operator) throws Exception { + Method method = + TableFunctionOperator.class.getDeclaredMethod( + "finishProcessor", List.class, ColumnBuilder.class); + method.setAccessible(true); + return (boolean) method.invoke(operator, Collections.emptyList(), null); + } + + @Test + public void pendingFinishReleasesWorkerAndSubmitsOnlyOnce() throws Exception { + Processor processor = new Processor(); + TableFunctionOperator operator = operator(processor); + assertFalse(finish(operator)); + assertSame(processor.future, operator.isBlocked()); + assertEquals(QUERY_DEADLINE_MILLIS, processor.deadlineMillis); + assertFalse(finish(operator)); + assertEquals(1, processor.submissions); + processor.future.set(null); + assertTrue(finish(operator)); + } + + @Test + public void finishFailureReachesQuery() throws Exception { + Processor processor = new Processor(); + TableFunctionOperator operator = operator(processor); + assertFalse(finish(operator)); + processor.future.setException(new IllegalArgumentException("invalid model input")); + try { + finish(operator); + fail("Expected query failure"); + } catch (InvocationTargetException e) { + assertTrue(e.getCause() instanceof ExecutionException); + assertEquals("invalid model input", e.getCause().getCause().getMessage()); + } + } + + @Test + public void closeCancelsPendingFinishAndDestroysProcessor() throws Exception { + Processor processor = new Processor(); + TableFunctionOperator operator = operator(processor); + assertFalse(finish(operator)); + operator.close(); + assertTrue(processor.future.isCancelled()); + assertTrue(processor.destroyed); + verify(local).close(); + } + + @Test + public void existingSynchronousProcessorIsUnchanged() throws Exception { + int[] finishes = {0}; + TableFunctionDataProcessor processor = + new TableFunctionDataProcessor() { + public void process(Record record, List builders, ColumnBuilder index) {} + + @Override + public void finish( + List builders, ColumnBuilder index, IoTDBLocal context) { + assertSame(local, context); + finishes[0]++; + } + }; + assertTrue(finish(operator(processor))); + assertEquals(1, finishes[0]); + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/tvf/TableFunctionOperatorTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/tvf/TableFunctionOperatorTest.java index 6606db879a830..388dac94a2c5b 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/tvf/TableFunctionOperatorTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/tvf/TableFunctionOperatorTest.java @@ -50,6 +50,7 @@ import org.junit.Assert; import org.junit.Test; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; @@ -198,6 +199,68 @@ public long ramBytesUsed() { }; } + @Test + public void testImplicitPartitionKeysWithFinishOnlyOutput() throws Exception { + FragmentInstanceId instanceId = + new FragmentInstanceId(new PlanFragmentId(new QueryId("partition_key_query"), 0), "key"); + FragmentInstanceStateMachine stateMachine = + new FragmentInstanceStateMachine(instanceId, instanceNotificationExecutor); + DriverContext driver = + new DriverContext(createFragmentInstanceContext(instanceId, stateMachine), 0); + driver.addOperatorContext(0, new PlanNodeId("child"), "child"); + TableFunctionProcessorProvider processorProvider = + new TableFunctionProcessorProvider() { + @Override + public TableFunctionDataProcessor getDataProcessor() { + return new TableFunctionDataProcessor() { + private int rowCount; + + @Override + public void process(Record input, List output, ColumnBuilder indexes) { + rowCount++; + } + + @Override + public void finish(List output, ColumnBuilder indexes) { + output.get(0).writeInt(rowCount); + } + }; + } + }; + + List keys = new ArrayList<>(); + List counts = new ArrayList<>(); + try (TableFunctionOperator operator = + new TableFunctionOperator( + driver.addOperatorContext(1, new PlanNodeId("finish"), "TableFunctionOperator"), + processorProvider, + constructChildOperator(driver), + Arrays.asList( + TSDataType.TIMESTAMP, TSDataType.STRING, TSDataType.DOUBLE, TSDataType.INT32), + Arrays.asList(TSDataType.INT32, TSDataType.STRING), + 1, + Collections.singletonList(2), + Collections.singletonList(1), + false, + Collections.singletonList(1), + false, + mock(IoTDBLocal.class), + -1L)) { + for (int step = 0; step < 64 && operator.hasNext(); step++) { + Assert.assertTrue(operator.isBlocked().isDone()); + TsBlock block = operator.next(); + if (block != null) { + assertEquals(1, block.getPositionCount()); + counts.add(block.getColumn(0).getInt(0)); + keys.add(block.getColumn(1).getBinary(0)); + } + } + Assert.assertFalse(operator.hasNext()); + } + assertEquals(Arrays.asList(D1_BINARY, D2_BINARY, D3_BINARY, D5_BINARY), keys); + assertEquals(Arrays.asList(3, 3, 2, 3), counts); + } + @Test public void testPartitionRecognizer() { QueryId queryId = new QueryId("stub_query"); @@ -382,7 +445,8 @@ private void appendRows( withPassThrough, Collections.emptyList(), false, - mock(IoTDBLocal.class))) { + mock(IoTDBLocal.class), + -1L)) { assertEquals(maxBlockSize, operator.calculateMaxReturnSize()); while (!operator.isFinished()) { operator.isBlocked(); @@ -453,7 +517,8 @@ public void process( false, Collections.singletonList(0), false, - mock(IoTDBLocal.class))) { + mock(IoTDBLocal.class), + -1L)) { while (!operator.isFinished()) { operator.isBlocked(); TsBlock block = operator.next(); @@ -528,7 +593,8 @@ public void beforeDestroy() { false, Collections.emptyList(), false, - ioTDBLocal); + ioTDBLocal, + -1L); operator.isBlocked(); Assert.assertNotNull(operator.next()); long retainedSizeBeforeClose = operator.ramBytesUsed(); diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/function/tvf/ForecastTableFunctionHandleTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/function/tvf/ForecastTableFunctionHandleTest.java new file mode 100644 index 0000000000000..68ab3964eec5a --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/function/tvf/ForecastTableFunctionHandleTest.java @@ -0,0 +1,61 @@ +/* + * 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. + */ + +package org.apache.iotdb.db.queryengine.plan.relational.function.tvf; + +import org.apache.iotdb.commons.queryengine.plan.relational.function.tvf.ForecastTableFunction.ForecastTableFunctionHandle; +import org.apache.iotdb.udf.api.type.Type; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +public class ForecastTableFunctionHandleTest { + private ForecastTableFunctionHandle handle() { + return new ForecastTableFunctionHandle( + true, + 2880, + "chronos2", + Collections.singletonMap("batch_size", "16"), + 96, + 123456L, + 3600000L, + Arrays.asList(Type.FLOAT, Type.DOUBLE)); + } + + @Test + public void testHandleRetainsLegacyBytes() { + byte[] legacyBytes = + Base64.getDecoder() + .decode( + "AAAACGNocm9ub3MyAAALQAAAAGAAAAAAAAHiQAAAAAAANu6AAQAAAAEA" + + "AAAKYmF0Y2hfc2l6ZQAAAAIxNgAAAAIDBA=="); + ForecastTableFunctionHandle expected = handle(); + ForecastTableFunctionHandle restored = new ForecastTableFunctionHandle(); + restored.deserialize(legacyBytes); + assertEquals(expected, restored); + assertEquals(expected.hashCode(), restored.hashCode()); + assertArrayEquals(legacyBytes, expected.serialize()); + } +} diff --git a/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template b/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template index 1db3f3271aae5..899f1c23c304d 100644 --- a/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template +++ b/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template @@ -1278,6 +1278,13 @@ query_cost_stat_window=0 # Datatype: int query_timeout_threshold=60000 +# Maximum input rows per partition for table FORECAST/CLASSIFY and tree FORECAST. +# Must be positive. When the window is full, retain the latest rows by timestamp. +# For equal timestamps, keep the most recent arrivals and serialize ties in arrival order. +# effectiveMode: restart +# Datatype: int +dn_ainode_max_input_length=2880 + # The maximum allowed concurrently executing queries # effectiveMode: restart # Datatype: int diff --git a/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/QueryMessages.java b/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/QueryMessages.java index 9264303974800..b61bda253d08a 100644 --- a/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/QueryMessages.java +++ b/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/QueryMessages.java @@ -21,6 +21,17 @@ public final class QueryMessages { + public static final String EXCEPTION_INPUT_WINDOW_CAPACITY_MUST_BE_POSITIVE_GOT_ARG_F2B64977 = + "Input window capacity must be positive, got %d"; + public static final String + LOG_ARG_INPUT_EXCEEDS_DN_AINODE_MAX_INPUT_LENGTH_ARG_RETAINING_THE_LATEST_ROWS_BY_TIME_517B0F70 = + "{} input exceeds dn_ainode_max_input_length={}; retaining the latest rows by time"; + public static final String + EXCEPTION_IOTDB_AINODE_INFERENCE_RPC_THREADS_MUST_BE_1_256_GOT_ARG_DB381A69 = + "iotdb.ainode.inference_rpc_threads must be 1..256, got %d"; + public static final String EXCEPTION_FORECAST_QUERY_DEADLINE_EXCEEDED_OR_QUERY_WAS_CANCELLED_AF239C66 = + "Forecast query deadline exceeded or query was cancelled"; + // ======================== PlanNode ======================== public static final String PLAN_NODE_NOT_SUPPORT_GET_TYPE = diff --git a/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/QueryMessages.java b/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/QueryMessages.java index d4007df3fb059..aebd412f239bb 100644 --- a/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/QueryMessages.java +++ b/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/QueryMessages.java @@ -21,6 +21,17 @@ public final class QueryMessages { + public static final String EXCEPTION_INPUT_WINDOW_CAPACITY_MUST_BE_POSITIVE_GOT_ARG_F2B64977 = + "输入窗口容量必须为正数,实际为 %d"; + public static final String + LOG_ARG_INPUT_EXCEEDS_DN_AINODE_MAX_INPUT_LENGTH_ARG_RETAINING_THE_LATEST_ROWS_BY_TIME_517B0F70 = + "{} 的输入行数超过 dn_ainode_max_input_length={},将按时间戳保留最新的行"; + public static final String + EXCEPTION_IOTDB_AINODE_INFERENCE_RPC_THREADS_MUST_BE_1_256_GOT_ARG_DB381A69 = + "iotdb.ainode.inference_rpc_threads 必须在 1 到 256 之间,实际为 %d"; + public static final String EXCEPTION_FORECAST_QUERY_DEADLINE_EXCEEDED_OR_QUERY_WAS_CANCELLED_AF239C66 = + "FORECAST 查询超时或已取消"; + // ======================== PlanNode ======================== public static final String PLAN_NODE_NOT_SUPPORT_GET_TYPE = diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/AsyncTableFunctionDataProcessor.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/AsyncTableFunctionDataProcessor.java new file mode 100644 index 0000000000000..9aa7d52a4526d --- /dev/null +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/AsyncTableFunctionDataProcessor.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.iotdb.commons.queryengine.plan.relational.function; + +import org.apache.iotdb.udf.api.relational.table.processor.TableFunctionDataProcessor; + +import org.apache.ratis.thirdparty.com.google.common.util.concurrent.ListenableFuture; +import org.apache.tsfile.block.column.ColumnBuilder; + +import java.util.List; + +/** Internal opt-in for processors whose finish performs blocking external I/O. */ +public interface AsyncTableFunctionDataProcessor extends TableFunctionDataProcessor { + default void setQueryDeadline(long deadlineMillis) {} + + ListenableFuture finishAsync( + List builders, ColumnBuilder passThroughIndexBuilder); +} diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/ITableFunctionAINodeService.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/ITableFunctionAINodeService.java index f35790ba97af0..3194a4fb95f90 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/ITableFunctionAINodeService.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/ITableFunctionAINodeService.java @@ -24,5 +24,45 @@ public interface ITableFunctionAINodeService { + int DEFAULT_MAX_INPUT_LENGTH = 2880; + + default int getMaxInputLength() { + return DEFAULT_MAX_INPUT_LENGTH; + } + TForecastResp forecast(TForecastReq req); + + default TForecastResp forecast( + TForecastReq req, long deadlineMillis, ForecastCancellation cancellation) { + return forecast(req); + } + + final class ForecastCancellation { + private boolean cancelled; + private Runnable invalidate; + + public synchronized boolean isCancelled() { + return cancelled; + } + + public synchronized boolean register(Runnable invalidate) { + if (cancelled) { + return false; + } + this.invalidate = invalidate; + return true; + } + + public synchronized void unregister() { + invalidate = null; + } + + public synchronized void cancel() { + cancelled = true; + if (invalidate != null) { + invalidate.run(); + invalidate = null; + } + } + } } diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/tvf/ClassifyTableFunction.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/tvf/ClassifyTableFunction.java index 945ea98797786..4421d852cfc44 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/tvf/ClassifyTableFunction.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/tvf/ClassifyTableFunction.java @@ -25,6 +25,8 @@ import org.apache.iotdb.commons.exception.SemanticException; import org.apache.iotdb.commons.i18n.QueryMessages; import org.apache.iotdb.commons.queryengine.plan.relational.utils.ResultColumnAppender; +import org.apache.iotdb.commons.queryengine.plan.udf.LatestTimeWindow; +import org.apache.iotdb.commons.queryengine.plan.udf.LatestTimeWindow.Sample; import org.apache.iotdb.commons.queryengine.plan.udf.TableUDFUtils; import org.apache.iotdb.rpc.TSStatusCode; import org.apache.iotdb.udf.api.exception.UDFException; @@ -59,7 +61,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashSet; -import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; @@ -114,7 +115,7 @@ public void deserialize(byte[] bytes) { int size = ReadWriteIOUtils.readInt(buffer); this.inputColumnTypes = new ArrayList<>(size); for (int i = 0; i < size; i++) { - inputColumnTypes.add(Type.valueOf(ReadWriteIOUtils.readString(buffer))); + inputColumnTypes.add(Type.valueOf(ReadWriteIOUtils.readByte(buffer))); } } @@ -139,7 +140,6 @@ public int hashCode() { public static final String TIMECOL_PARAMETER_NAME = "TIMECOL"; private static final String DEFAULT_TIME_COL = "time"; private static final String DEFAULT_OUTPUT_COLUMN_NAME = "category"; - private static final int MAX_INPUT_LENGTH = 2880; private static final Set ALLOWED_INPUT_TYPES = new HashSet<>(); @@ -217,13 +217,17 @@ public TableFunctionAnalysis analyze(Map arguments) throws UDF properColumnSchemaBuilder.addField(DEFAULT_OUTPUT_COLUMN_NAME, Type.INT32); ClassifyTableFunctionHandle functionHandle = - new ClassifyTableFunctionHandle(modelId, MAX_INPUT_LENGTH, inputColumnTypes); + new ClassifyTableFunctionHandle( + modelId, + TableUDFUtils.getTableFunctionAINodeService().getMaxInputLength(), + inputColumnTypes); // outputColumnSchema return TableFunctionAnalysis.builder() .properColumnSchema(properColumnSchemaBuilder.build()) .handle(functionHandle) .requiredColumns(INPUT_PARAMETER_NAME, requiredIndexList) + .requireRecordSnapshot(false) .build(); } @@ -251,28 +255,26 @@ public TableFunctionDataProcessor getDataProcessor() { }; } - private static class ClassifyDataProcessor implements TableFunctionDataProcessor { + static class ClassifyDataProcessor implements TableFunctionDataProcessor { private static final TsBlockSerde SERDE = new TsBlockSerde(); private final String modelId; - private final int maxInputLength; - private final LinkedList inputRecords; + private final LatestTimeWindow inputWindow; private final TsBlockBuilder inputTsBlockBuilder; private final List inputColumnAppenderList; private final List resultColumnAppenderList; public ClassifyDataProcessor(ClassifyTableFunctionHandle functionHandle) { this.modelId = functionHandle.modelId; - this.maxInputLength = functionHandle.maxInputLength; - this.inputRecords = new LinkedList<>(); + this.inputWindow = new LatestTimeWindow<>(functionHandle.maxInputLength, "Table CLASSIFY"); List inputTsDataTypeList = new ArrayList<>(functionHandle.inputColumnTypes.size()); this.inputColumnAppenderList = new ArrayList<>(functionHandle.inputColumnTypes.size()); for (Type type : functionHandle.inputColumnTypes) { // AINode currently only accept double input inputTsDataTypeList.add(TSDataType.DOUBLE); - inputColumnAppenderList.add(createResultColumnAppender(Type.DOUBLE)); + inputColumnAppenderList.add(createResultColumnAppender(type)); } this.inputTsBlockBuilder = new TsBlockBuilder(inputTsDataTypeList); this.resultColumnAppenderList = new ArrayList<>(1); @@ -284,32 +286,42 @@ public void process( Record input, List properColumnBuilders, ColumnBuilder passThroughIndexBuilder) { - // only keep at most maxInputLength rows - if (maxInputLength != 0 && inputRecords.size() == maxInputLength) { - inputRecords.removeFirst(); - } - inputRecords.add(input); + inputWindow.add( + input.getLong(0), + () -> { + double[] values = new double[inputColumnAppenderList.size()]; + for (int column = 0; column < values.length; column++) { + int inputIndex = column + 1; + values[column] = + input.isNull(inputIndex) + ? 0.0 + : inputColumnAppenderList.get(column).getDouble(input, inputIndex); + } + return values; + }); } @Override public void finish( List properColumnBuilders, ColumnBuilder passThroughIndexBuilder) { - // time column - long inputStartTime = inputRecords.getFirst().getLong(0); - long inputEndTime = inputRecords.getLast().getLong(0); - if (inputEndTime < inputStartTime) { - throw new SemanticException( - String.format( - QueryMessages.INPUT_END_TIME_LESS_THAN_START_TIME, inputStartTime, inputEndTime)); + List> samples = inputWindow.drainInTimeOrder(); + if (samples.isEmpty()) { + return; } - int outputLength = inputRecords.size(); - for (Record inputRecord : inputRecords) { - properColumnBuilders.get(0).writeLong(inputRecord.getLong(0)); + int outputLength = samples.size(); + for (Sample sample : samples) { + properColumnBuilders.get(0).writeLong(sample.getTime()); + inputTsBlockBuilder.getTimeColumnBuilder().writeLong(sample.getTime()); + double[] values = sample.getValue(); + for (int column = 0; column < values.length; column++) { + inputTsBlockBuilder.getColumnBuilder(column).writeDouble(values[column]); + } + inputTsBlockBuilder.declarePosition(); } // predicated columns - TsBlock predicatedResult = classify(); + TsBlock predicatedResult = classify(inputTsBlockBuilder.build(), outputLength); if (predicatedResult.getPositionCount() != outputLength) { throw new IoTDBRuntimeException( String.format( @@ -337,32 +349,10 @@ public void finish( } } - private TsBlock classify() { - int outputLength = inputRecords.size(); - // construct inputTSBlock for AINode - while (!inputRecords.isEmpty()) { - Record row = inputRecords.removeFirst(); - inputTsBlockBuilder.getTimeColumnBuilder().writeLong(row.getLong(0)); - for (int i = 1, size = row.size(); i < size; i++) { - // we set null input to 0.0 - if (row.isNull(i)) { - inputTsBlockBuilder.getColumnBuilder(i - 1).writeDouble(0.0); - } else { - // need to transform other types to DOUBLE - inputTsBlockBuilder - .getColumnBuilder(i - 1) - .writeDouble(inputColumnAppenderList.get(i - 1).getDouble(row, i)); - } - } - inputTsBlockBuilder.declarePosition(); - } - TsBlock inputData = inputTsBlockBuilder.build(); - + private TsBlock classify(TsBlock inputData, int outputLength) { TForecastResp resp; try { - resp = - TableUDFUtils.getTableFunctionAINodeService() - .forecast(new TForecastReq(modelId, SERDE.serialize(inputData), outputLength)); + resp = invokeForecast(new TForecastReq(modelId, SERDE.serialize(inputData), outputLength)); } catch (IOException e) { throw new RuntimeException(e); } @@ -374,5 +364,9 @@ private TsBlock classify() { } return SERDE.deserialize(resp.forecastResult.get(0)); } + + TForecastResp invokeForecast(TForecastReq request) { + return TableUDFUtils.getTableFunctionAINodeService().forecast(request); + } } } diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/tvf/ForecastTableFunction.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/tvf/ForecastTableFunction.java index 4c58e5855ce6a..9fd6aeb975294 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/tvf/ForecastTableFunction.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/tvf/ForecastTableFunction.java @@ -24,7 +24,11 @@ import org.apache.iotdb.commons.exception.IoTDBRuntimeException; import org.apache.iotdb.commons.exception.SemanticException; import org.apache.iotdb.commons.i18n.QueryMessages; +import org.apache.iotdb.commons.queryengine.plan.relational.function.AsyncTableFunctionDataProcessor; +import org.apache.iotdb.commons.queryengine.plan.relational.function.ITableFunctionAINodeService.ForecastCancellation; import org.apache.iotdb.commons.queryengine.plan.relational.utils.ResultColumnAppender; +import org.apache.iotdb.commons.queryengine.plan.udf.LatestTimeWindow; +import org.apache.iotdb.commons.queryengine.plan.udf.LatestTimeWindow.Sample; import org.apache.iotdb.commons.queryengine.plan.udf.TableUDFUtils; import org.apache.iotdb.rpc.TSStatusCode; import org.apache.iotdb.udf.api.relational.TableFunction; @@ -42,6 +46,10 @@ import org.apache.iotdb.udf.api.relational.table.specification.TableParameterSpecification; import org.apache.iotdb.udf.api.type.Type; +import org.apache.ratis.thirdparty.com.google.common.util.concurrent.ListenableFuture; +import org.apache.ratis.thirdparty.com.google.common.util.concurrent.ListeningExecutorService; +import org.apache.ratis.thirdparty.com.google.common.util.concurrent.MoreExecutors; +import org.apache.ratis.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.tsfile.block.column.Column; import org.apache.tsfile.block.column.ColumnBuilder; import org.apache.tsfile.enums.TSDataType; @@ -57,14 +65,16 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.apache.iotdb.commons.queryengine.plan.relational.function.tvf.TableFunctionUtils.checkType; @@ -197,7 +207,6 @@ public int hashCode() { protected static final String IS_INPUT_COLUMN_NAME = "is_input"; protected static final String OPTIONS_PARAMETER_NAME = "MODEL_OPTIONS"; protected static final String DEFAULT_OPTIONS = ""; - protected static final int MAX_INPUT_LENGTH = 2880; @Override public List getArgumentsSpecifications() { @@ -306,14 +315,6 @@ public TableFunctionAnalysis analyze(Map arguments) { properColumnSchemaBuilder.addField(fieldName.get(), columnType); } - if (targetColumnTypes.size() > 1) { - throw new SemanticException( - String.format( - QueryMessages.TARGETS_TOO_MANY_COLUMNS, - TARGETS_PARAMETER_NAME, - targetColumnTypes.size())); - } - boolean keepInput = (boolean) ((ScalarArgument) arguments.get(KEEP_INPUT_PARAMETER_NAME)).getValue(); if (keepInput) { @@ -326,7 +327,7 @@ public TableFunctionAnalysis analyze(Map arguments) { ForecastTableFunctionHandle functionHandle = new ForecastTableFunctionHandle( keepInput, - MAX_INPUT_LENGTH, + TableUDFUtils.getTableFunctionAINodeService().getMaxInputLength(), modelId, parseOptions(options), outputLength, @@ -339,6 +340,7 @@ public TableFunctionAnalysis analyze(Map arguments) { .properColumnSchema(properColumnSchemaBuilder.build()) .handle(functionHandle) .requiredColumns(TARGETS_PARAMETER_NAME, requiredIndexList) + .requireRecordSnapshot(false) .build(); } @@ -358,30 +360,92 @@ public TableFunctionDataProcessor getDataProcessor() { }; } - protected static class ForecastDataProcessor implements TableFunctionDataProcessor { + protected static class ForecastDataProcessor implements AsyncTableFunctionDataProcessor { protected static final TsBlockSerde SERDE = new TsBlockSerde(); + private static final int INFERENCE_RPC_THREADS = inferenceRpcThreads(); + + private static int inferenceRpcThreads() { + String value = System.getProperty("iotdb.ainode.inference_rpc_threads"); + if (value == null) { + return Math.min(32, Math.max(2, Runtime.getRuntime().availableProcessors())); + } + int threads = Integer.parseInt(value); + if (threads < 1 || threads > 256) { + throw new IllegalArgumentException( + String.format( + QueryMessages + .EXCEPTION_IOTDB_AINODE_INFERENCE_RPC_THREADS_MUST_BE_1_256_GOT_ARG_DB381A69, + threads)); + } + return threads; + } + + private static final ListeningExecutorService INFERENCE_EXECUTOR = + MoreExecutors.listeningDecorator( + new ThreadPoolExecutor( + INFERENCE_RPC_THREADS, + INFERENCE_RPC_THREADS, + 60, + TimeUnit.SECONDS, + new ArrayBlockingQueue<>(256), + new ThreadFactoryBuilder() + .setNameFormat("AINode-Inference-%d") + .setDaemon(true) + .build(), + new ThreadPoolExecutor.AbortPolicy())); + private final ForecastCancellation cancellation = new ForecastCancellation(); + private long queryDeadlineMillis = -1L; + + @Override + public void setQueryDeadline(long deadlineMillis) { + queryDeadlineMillis = deadlineMillis; + } + + private void checkCancelled() { + if (cancellation.isCancelled() + || Thread.currentThread().isInterrupted() + || (queryDeadlineMillis > 0 && queryDeadlineMillis <= System.currentTimeMillis())) { + throw new CancellationException( + QueryMessages + .EXCEPTION_FORECAST_QUERY_DEADLINE_EXCEEDED_OR_QUERY_WAS_CANCELLED_AF239C66); + } + } + + @Override + public ListenableFuture finishAsync( + List builders, ColumnBuilder passThroughIndexBuilder) { + return INFERENCE_EXECUTOR.submit( + () -> { + checkCancelled(); + finish(builders, passThroughIndexBuilder); + }); + } + + @Override + public void beforeDestroy() { + cancellation.cancel(); + } + protected final String modelId; - private final int maxInputLength; protected final int outputLength; private final long outputStartTime; private final long outputInterval; private final boolean keepInput; protected final Map options; - protected final LinkedList inputRecords; + private final LatestTimeWindow inputWindow; protected final List resultColumnAppenderList; protected final TsBlockBuilder inputTsBlockBuilder; public ForecastDataProcessor(ForecastTableFunctionHandle functionHandle) { this.modelId = functionHandle.modelId; - this.maxInputLength = functionHandle.maxInputLength; this.outputLength = functionHandle.outputLength; this.outputStartTime = functionHandle.outputStartTime; this.outputInterval = functionHandle.outputInterval; this.keepInput = functionHandle.keepInput; this.options = functionHandle.options; - this.inputRecords = new LinkedList<>(); + this.inputWindow = new LatestTimeWindow<>(functionHandle.maxInputLength, "Table FORECAST"); this.resultColumnAppenderList = new ArrayList<>(functionHandle.targetColumntypes.size()); List tsDataTypeList = new ArrayList<>(functionHandle.targetColumntypes.size()); for (Type type : functionHandle.targetColumntypes) { @@ -418,11 +482,19 @@ public void process( properColumnBuilders.get(columnSize - 1).writeBoolean(true); } - // only keep at most maxInputLength rows - if (maxInputLength != 0 && inputRecords.size() == maxInputLength) { - inputRecords.removeFirst(); - } - inputRecords.add(input); + inputWindow.add( + input.getLong(0), + () -> { + double[] values = new double[resultColumnAppenderList.size()]; + for (int column = 0; column < values.length; column++) { + int inputIndex = column + 1; + values[column] = + input.isNull(inputIndex) + ? Double.NaN + : resultColumnAppenderList.get(column).getDouble(input, inputIndex); + } + return values; + }); } @Override @@ -431,20 +503,15 @@ public void finish( int columnSize = properColumnBuilders.size(); - // sort inputRecords in ascending order by timestamp - inputRecords.sort(Comparator.comparingLong(r -> r.getLong(0))); - - // time column - long inputStartTime = inputRecords.getFirst().getLong(0); - long inputEndTime = inputRecords.getLast().getLong(0); - if (inputEndTime < inputStartTime) { - throw new SemanticException( - String.format( - QueryMessages.INPUT_END_TIME_LESS_THAN_START_TIME, inputStartTime, inputEndTime)); + List> samples = inputWindow.drainInTimeOrder(); + if (samples.isEmpty()) { + return; } + int inputLength = samples.size(); + long inputStartTime = samples.get(0).getTime(); + long inputEndTime = samples.get(inputLength - 1).getTime(); long interval = - calculateForecastInterval( - inputStartTime, inputEndTime, inputRecords.size(), outputInterval); + calculateForecastInterval(inputStartTime, inputEndTime, inputLength, outputInterval); long outputTime = calculateForecastStartTime(inputEndTime, outputStartTime, interval); if (outputTime <= inputEndTime) { throw new SemanticException( @@ -459,7 +526,15 @@ public void finish( } // predicated columns - TsBlock predicatedResult = forecast(); + for (Sample sample : samples) { + inputTsBlockBuilder.getTimeColumnBuilder().writeLong(sample.getTime()); + double[] values = sample.getValue(); + for (int column = 0; column < values.length; column++) { + inputTsBlockBuilder.getColumnBuilder(column).writeDouble(values[column]); + } + inputTsBlockBuilder.declarePosition(); + } + TsBlock predicatedResult = forecast(inputTsBlockBuilder.build()); if (predicatedResult.getPositionCount() != outputLength) { throw new IoTDBRuntimeException( String.format( @@ -495,33 +570,13 @@ public void finish( } } - protected TsBlock forecast() { - // construct inputTSBlock for AINode - while (!inputRecords.isEmpty()) { - Record row = inputRecords.removeFirst(); - inputTsBlockBuilder.getTimeColumnBuilder().writeLong(row.getLong(0)); - for (int i = 1, size = row.size(); i < size; i++) { - // we set null input to 0.0 - if (row.isNull(i)) { - inputTsBlockBuilder.getColumnBuilder(i - 1).writeDouble(0.0); - } else { - // need to transform other types to DOUBLE - inputTsBlockBuilder - .getColumnBuilder(i - 1) - .writeDouble(resultColumnAppenderList.get(i - 1).getDouble(row, i)); - } - } - inputTsBlockBuilder.declarePosition(); - } - TsBlock inputData = inputTsBlockBuilder.build(); - + private TsBlock forecast(TsBlock inputData) { TForecastResp resp; try { resp = - TableUDFUtils.getTableFunctionAINodeService() - .forecast( - new TForecastReq(modelId, SERDE.serialize(inputData), outputLength) - .setOptions(options)); + invokeForecast( + new TForecastReq(modelId, SERDE.serialize(inputData), outputLength) + .setOptions(options)); } catch (IOException e) { throw new RuntimeException(e); } @@ -544,5 +599,10 @@ protected TsBlock forecast() { } return res; } + + TForecastResp invokeForecast(TForecastReq request) { + return TableUDFUtils.getTableFunctionAINodeService() + .forecast(request, queryDeadlineMillis, cancellation); + } } } diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/udf/LatestTimeWindow.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/udf/LatestTimeWindow.java new file mode 100644 index 0000000000000..c834e59d8fdc7 --- /dev/null +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/udf/LatestTimeWindow.java @@ -0,0 +1,103 @@ +/* + * 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. + */ + +package org.apache.iotdb.commons.queryengine.plan.udf; + +import org.apache.iotdb.commons.i18n.QueryMessages; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.PriorityQueue; +import java.util.function.Supplier; + +public final class LatestTimeWindow { + private static final Logger LOGGER = LoggerFactory.getLogger(LatestTimeWindow.class); + private static final Comparator> TIME_ORDER = + Comparator.>comparingLong(Sample::getTime) + .thenComparingLong(sample -> sample.arrivalOrder); + + private final int capacity; + private final String functionName; + private final PriorityQueue> samples = new PriorityQueue<>(TIME_ORDER); + private long arrivalOrder; + private boolean warned; + + public LatestTimeWindow(int capacity, String functionName) { + if (capacity <= 0) { + throw new IllegalArgumentException( + String.format( + QueryMessages.EXCEPTION_INPUT_WINDOW_CAPACITY_MUST_BE_POSITIVE_GOT_ARG_F2B64977, + capacity)); + } + this.capacity = capacity; + this.functionName = functionName; + } + + public void add(long time, Supplier value) { + if (samples.size() == capacity) { + if (!warned) { + LOGGER.warn( + QueryMessages + .LOG_ARG_INPUT_EXCEEDS_DN_AINODE_MAX_INPUT_LENGTH_ARG_RETAINING_THE_LATEST_ROWS_BY_TIME_517B0F70, + functionName, + capacity); + warned = true; + } + if (time < samples.element().getTime()) { + return; + } + Sample sample = new Sample<>(time, arrivalOrder++, value.get()); + samples.remove(); + samples.add(sample); + } else { + samples.add(new Sample<>(time, arrivalOrder++, value.get())); + } + } + + public List> drainInTimeOrder() { + List> ordered = new ArrayList<>(samples); + samples.clear(); + ordered.sort(TIME_ORDER); + return ordered; + } + + public static final class Sample { + private final long time; + private final long arrivalOrder; + private final T value; + + private Sample(long time, long arrivalOrder, T value) { + this.time = time; + this.arrivalOrder = arrivalOrder; + this.value = value; + } + + public long getTime() { + return time; + } + + public T getValue() { + return value; + } + } +} diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/udf/UDTFForecast.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/udf/UDTFForecast.java index de6bd3110072f..7b02ddbdea4df 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/udf/UDTFForecast.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/udf/UDTFForecast.java @@ -23,6 +23,7 @@ import org.apache.iotdb.ainode.rpc.thrift.TForecastResp; import org.apache.iotdb.commons.exception.IoTDBRuntimeException; import org.apache.iotdb.commons.i18n.QueryMessages; +import org.apache.iotdb.commons.queryengine.plan.udf.LatestTimeWindow.Sample; import org.apache.iotdb.rpc.TSStatusCode; import org.apache.iotdb.udf.api.UDTF; import org.apache.iotdb.udf.api.access.Row; @@ -41,7 +42,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; -import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; @@ -54,14 +54,13 @@ public class UDTFForecast implements UDTF { private static final TsBlockSerde serde = new TsBlockSerde(); private String model_id; - private int maxInputLength; private int outputLength; private long outputStartTime; private long outputInterval; private boolean keepInput; Map options; List types; - private LinkedList inputRows; + private LatestTimeWindow inputWindow; private TsBlockBuilder inputTsBlockBuilder; private static final Set ALLOWED_INPUT_TYPES = new HashSet<>(); @@ -84,7 +83,6 @@ public class UDTFForecast implements UDTF { private static final Boolean DEFAULT_KEEP_INPUT = Boolean.FALSE; private static final String OPTIONS_PARAMETER_NAME = "MODEL_OPTIONS"; private static final String DEFAULT_OPTIONS = ""; - private static final int MAX_INPUT_LENGTH = 2880; private void checkType() { for (Type type : this.types) { @@ -106,8 +104,6 @@ public void beforeStart(UDFParameters parameters, UDTFConfigurations configurati if (this.model_id == null || this.model_id.isEmpty()) { throw new IllegalArgumentException(QueryMessages.MODEL_ID_MUST_BE_PROVIDED); } - this.maxInputLength = MAX_INPUT_LENGTH; - this.outputInterval = parameters.getLongOrDefault(OUTPUT_INTERVAL, DEFAULT_OUTPUT_INTERVAL); this.outputLength = parameters.getIntOrDefault(OUTPUT_LENGTH_PARAMETER_NAME, DEFAULT_OUTPUT_LENGTH); @@ -123,7 +119,9 @@ public void beforeStart(UDFParameters parameters, UDTFConfigurations configurati Collectors.toMap( arr -> arr[0].trim(), arr -> arr[1].trim(), (v1, v2) -> v2 // 如果 key 重复,保留后一个 )); - this.inputRows = new LinkedList<>(); + this.inputWindow = + new LatestTimeWindow<>( + TableUDFUtils.getTableFunctionAINodeService().getMaxInputLength(), "Tree FORECAST"); List tsDataTypeList = new ArrayList<>(this.types.size() - 1); for (int i = 0; i < this.types.size(); i++) { tsDataTypeList.add(TSDataType.DOUBLE); @@ -185,29 +183,22 @@ public void transform(Row row, PointCollector collector) throws Exception { setByType(row, collector); } - if (maxInputLength != 0 && inputRows.size() >= maxInputLength) { - // If the input rows exceed the maximum length, remove the oldest row - inputRows.removeFirst(); - } - inputRows.add(row); + inputWindow.add(row.getTime(), () -> row); } - private TsBlock forecast() throws Exception { - // Build the input data which will be sent to AINode - while (!inputRows.isEmpty()) { - Row row = inputRows.removeFirst(); - inputTsBlockBuilder.getTimeColumnBuilder().writeLong(row.getTime()); - setByType(row, inputTsBlockBuilder); + private TsBlock forecast(List> samples) throws Exception { + for (Sample sample : samples) { + inputTsBlockBuilder.getTimeColumnBuilder().writeLong(sample.getTime()); + setByType(sample.getValue(), inputTsBlockBuilder); inputTsBlockBuilder.declarePosition(); } TsBlock inputData = inputTsBlockBuilder.build(); TForecastResp resp = - TableUDFUtils.getTableFunctionAINodeService() - .forecast( - new TForecastReq(model_id, serde.serialize(inputData), outputLength) - .setOptions(options)); + invokeForecast( + new TForecastReq(model_id, serde.serialize(inputData), outputLength) + .setOptions(options)); if (resp.getStatus().getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode()) { throw new IoTDBRuntimeException( @@ -220,24 +211,28 @@ private TsBlock forecast() throws Exception { return serde.deserialize(resp.forecastResult.get(0)); } + protected TForecastResp invokeForecast(TForecastReq request) { + return TableUDFUtils.getTableFunctionAINodeService().forecast(request); + } + @Override public void terminate(PointCollector collector) throws Exception { - long inputStartTime = inputRows.get(0).getTime(); - long inputEndTime = inputRows.get(inputRows.size() - 1).getTime(); - if (inputStartTime > inputEndTime) { - throw new IllegalArgumentException( - String.format( - QueryMessages.INPUT_END_TIME_LESS_THAN_START_TIME, inputStartTime, inputEndTime)); + List> samples = inputWindow.drainInTimeOrder(); + if (samples.isEmpty()) { + return; } + int inputLength = samples.size(); + long inputStartTime = samples.get(0).getTime(); + long inputEndTime = samples.get(inputLength - 1).getTime(); long interval = - calculateForecastInterval(inputStartTime, inputEndTime, inputRows.size(), outputInterval); + calculateForecastInterval(inputStartTime, inputEndTime, inputLength, outputInterval); long outputTime = calculateForecastStartTime(inputEndTime, this.outputStartTime, interval); long[] outputTimes = new long[this.outputLength]; for (int i = 0; i < this.outputLength; i++) { outputTimes[i] = calculateForecastOutputTime(outputTime, interval, i); } - TsBlock forecastResult = forecast(); + TsBlock forecastResult = forecast(samples); if (forecastResult.getPositionCount() != this.outputLength) { throw new IllegalArgumentException( String.format(