future.py Source File

future.py Source File#

Runtime Library: future.py Source File
Runtime Library v0.30
Mobilint SDK qb
future.py
Go to the documentation of this file.
1
4
5from typing import List, Optional, Union
6
7import numpy as np
8
9import maccel.maccel as _cMaccel
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[Union[_cMaccel.FutureFloat, _cMaccel.FutureInt8]] = None,
32 _inputs: Optional[List[np.ndarray]] = None,
33 ):
34 # If parameters are None, it indicates invalid access.
35 # Set FutureFloat by default just to raise error with `get` method.
36 self._future = _future if _future is not None else _cMaccel.FutureFloat()
37 # self._inputs holds user inputs to prevent them from being garbage collected
38 # before asynchronous inference is completed.
39 self._inputs = _inputs
40
41 @classmethod
42 def from_cpp(
43 cls,
44 _future: Union[_cMaccel.FutureFloat, _cMaccel.FutureInt8],
45 _inputs: List[np.ndarray],
46 ):
47 return cls(_future, _inputs)
48
49 def wait_for(self, timeout_ms: int) -> bool:
50 """
51 @brief Waits for asynchronous inference to complete or until the timeout elapses.
52
53 @note This method is safe to call multiple times. Calling it with
54 a timeout of zero (i.e., `wait_for(0)`) performs a non-blocking
55 check to see whether asynchronous inference has already completed.
56
57 @param[in] timeout_ms Maximum duration to wait, in milliseconds.
58
59 @return True if inference completed before the timeout, false otherwise.
60 """
61 return self._future.wait_for(timeout_ms)
62
63 def get(self) -> List[np.ndarray]:
64 """
65 @brief Blocks until asynchronous inference completes and retrieves the output.
66
67 @note This method should be called only once per Future. If called again,
68 the return value will be invalid, and it will raise maccel.MAccelError
69 "Future_NotValid".
70
71 @return A list of numpy ndarray containing the inference output.
72 """
73 outputs = self._future.get()
74 self._inputs = None
75 return [np.asarray(o) for o in outputs]
76
77
78
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:49
List[np.ndarray] get(self)
Blocks until asynchronous inference completes and retrieves the output.
Definition future.py:63