future.py Source File

future.py Source File#

SDK qb Runtime Library: future.py Source File
SDK qb Runtime Library v1.0
MCS001-
future.py
Go to the documentation of this file.
1
4
5from typing import List, Optional, Union
6
7import numpy as np
8
9import qbruntime.qbruntime as _cQbRuntime
10
11
14
15
16class Future:
17 """
18 @brief Represents a future for retrieving the result of asynchronous inference.
19
20 This class provides a mechanism similar to C++11 std::future, allowing access to
21 the result of an asynchronous inference operation initiated via `Model.infer_async()`.
22 For details on C++11 std::future, refer to https://en.cppreference.com/w/cpp/thread/future.html .
23
24 The Future object enables the caller to:
25 - Wait for the inference to complete (`wait_for`)
26 - Block until completion and retrieve the output (`get`)
27 """
28
29 def __init__(
30 self,
31 _future: Optional[
32 Union[_cQbRuntime.FutureFloat, _cQbRuntime.FutureInt8]
33 ] = None,
34 _inputs: Optional[List[np.ndarray]] = None,
35 ):
36 # If parameters are None, it indicates invalid access.
37 # Set FutureFloat by default just to raise error with `get` method.
38 self._future = _future if _future is not None else _cQbRuntime.FutureFloat()
39 # self._inputs holds user inputs to prevent them from being garbage collected
40 # before asynchronous inference is completed.
41 self._inputs = _inputs
42
43 @classmethod
44 def from_cpp(
45 cls,
46 _future: Union[_cQbRuntime.FutureFloat, _cQbRuntime.FutureInt8],
47 _inputs: List[np.ndarray],
48 ):
49 return cls(_future, _inputs)
50
51 def wait_for(self, timeout_ms: int) -> bool:
52 """
53 @brief Waits for asynchronous inference to complete or until the timeout elapses.
54
55 @note This method is safe to call multiple times. Calling it with
56 a timeout of zero (i.e., `wait_for(0)`) performs a non-blocking
57 check to see whether asynchronous inference has already completed.
58
59 @param[in] timeout_ms Maximum duration to wait, in milliseconds.
60
61 @return True if inference completed before the timeout, false otherwise.
62 """
63 return self._future.wait_for(timeout_ms)
64
65 def get(self) -> List[np.ndarray]:
66 """
67 @brief Blocks until asynchronous inference completes and retrieves the output.
68
69 @note This method should be called only once per Future. If called again,
70 the return value will be invalid, and it will raise qbruntime.QbRuntimeError
71 "Future_NotValid".
72
73 @return A list of numpy ndarray containing the inference output.
74 """
75 outputs = self._future.get()
76 self._inputs = None
77 return [np.asarray(o) for o in outputs]
78
79
80
Represents a future for retrieving the result of asynchronous inference.
Definition future.py:16
bool wait_for(self, int timeout_ms)
Waits for asynchronous inference to complete or until the timeout elapses.
Definition future.py:51
List[np.ndarray] get(self)
Blocks until asynchronous inference completes and retrieves the output.
Definition future.py:65