mirror of
https://github.com/saymrwulf/onnxruntime.git
synced 2026-07-22 19:23:30 +00:00
### Description Merge main to WindowsAI ### Motivation and Context <!-- - Why is this change required? What problem does it solve? - If it fixes an open issue, please link to the issue here. --> --------- Signed-off-by: Nash <george.nash@intel.com> Signed-off-by: Yiming Hu <yiming.hu@amd.com> Signed-off-by: Liqun Fu <liqfu@microsoft.com> Co-authored-by: Kaz Nishimura <kazssym@linuxfront.com> Co-authored-by: Tianlei Wu <tlwu@microsoft.com> Co-authored-by: Nat Kershaw (MSFT) <nakersha@microsoft.com> Co-authored-by: Yulong Wang <7679871+fs-eire@users.noreply.github.com> Co-authored-by: Changming Sun <chasun@microsoft.com> Co-authored-by: zesongw <zesong.wang@intel.com> Co-authored-by: Yi Zhang <zhanyi@microsoft.com> Co-authored-by: Dmitri Smirnov <yuslepukhin@users.noreply.github.com> Co-authored-by: Yifan Li <109183385+yf711@users.noreply.github.com> Co-authored-by: simonjub <78098752+simonjub@users.noreply.github.com> Co-authored-by: PeixuanZuo <94887879+PeixuanZuo@users.noreply.github.com> Co-authored-by: Adrian Lizarraga <adlizarraga@microsoft.com> Co-authored-by: Edward Chen <18449977+edgchen1@users.noreply.github.com> Co-authored-by: Arthur Islamov <arthur@islamov.ai> Co-authored-by: Jambay Kinley <jambaykinley@microsoft.com> Co-authored-by: Justin Chu <justinchuby@users.noreply.github.com> Co-authored-by: Wei-Sheng Chin <wschin@outlook.com> Co-authored-by: Bowen Bao <bowbao@microsoft.com> Co-authored-by: Hariharan Seshadri <shariharan91@gmail.com> Co-authored-by: Numfor Tiapo <numsmt2@gmail.com> Co-authored-by: Vincent Wang <wangwchpku@outlook.com> Co-authored-by: Pranav Sharma <prs@microsoft.com> Co-authored-by: George Nash <george.nash@intel.com> Co-authored-by: Abhishek Jindal <abjindal@microsoft.com> Co-authored-by: pengwa <pengwa@microsoft.com> Co-authored-by: Yiming Hu <woinck@users.noreply.github.com> Co-authored-by: Jiajia Qin <jiajia.qin@intel.com> Co-authored-by: Lukas Berbuer <36054362+lukasberbuer@users.noreply.github.com> Co-authored-by: Wanming Lin <wanming.lin@intel.com> Co-authored-by: Xavier Dupré <xadupre@users.noreply.github.com> Co-authored-by: aimilefth <60664743+aimilefth@users.noreply.github.com> Co-authored-by: Baiju Meswani <bmeswani@microsoft.com> Co-authored-by: Adam Pocock <adam.pocock@oracle.com> Co-authored-by: Chi Lo <54722500+chilo-ms@users.noreply.github.com> Co-authored-by: RandySheriffH <48490400+RandySheriffH@users.noreply.github.com> Co-authored-by: Randy Shuai <rashuai@microsoft.com> Co-authored-by: Vadym Stupakov <vadim.stupakov@gmail.com> Co-authored-by: Jian Chen <cjian@microsoft.com> Co-authored-by: Brian Lambert <98757707+brian-pieces@users.noreply.github.com> Co-authored-by: Nicolò Lucchesi <nicolo.lucchesi@gmail.com> Co-authored-by: liqun Fu <liqfu@microsoft.com> Co-authored-by: trajep <trajepl@gmail.com> Co-authored-by: Scott McKay <skottmckay@gmail.com> Co-authored-by: Mustafa Ateş Uzun <mustafauzun0@gmail.com> Co-authored-by: MistEO <mistereo@hotmail.com> Co-authored-by: satyajandhyala <satya.k.jandhyala@gmail.com> Co-authored-by: shaahji <96227573+shaahji@users.noreply.github.com> Co-authored-by: Rachel Guo <35738743+YUNQIUGUO@users.noreply.github.com> Co-authored-by: rachguo <rachguo@rachguos-Mini.attlocal.net> Co-authored-by: Caroline Zhu <wolfivyaura@gmail.com> Co-authored-by: Caroline Zhu <carolinezhu@microsoft.com> Co-authored-by: Guenther Schmuelling <guschmue@microsoft.com> Co-authored-by: xhcao <xinghua.cao@intel.com> Co-authored-by: Ella Charlaix <80481427+echarlaix@users.noreply.github.com> Co-authored-by: Xu Xing <xing.xu@intel.com> Co-authored-by: Hector Li <hecli@microsoft.com> Co-authored-by: Ye Wang <52801275+wangyems@users.noreply.github.com> Co-authored-by: Your Name <you@example.com> Co-authored-by: Benedikt Hilmes <benedikt.hilmes@rwth-aachen.de> Co-authored-by: rachguo <rachguo@rachguos-Mac-mini.local> Co-authored-by: George Wu <jywu@microsoft.com> Co-authored-by: JiCheng <wejoncy@163.com> Co-authored-by: Sheil Kumar <smk2007@gmail.com> Co-authored-by: Sheil Kumar <sheilk@microsoft.com> Co-authored-by: cloudhan <guangyunhan@microsoft.com> Co-authored-by: kyoshisuki <143475866+kyoshisuki@users.noreply.github.com> Co-authored-by: aciddelgado <139922440+aciddelgado@users.noreply.github.com> Co-authored-by: tlwu@microsoft.com <tlwu@a100.crj0ad2y1kku1j4yxl4sj10o4e.gx.internal.cloudapp.net> Co-authored-by: Maximilian Müller <44298237+gedoensmax@users.noreply.github.com> Co-authored-by: Tang, Cheng <souptc@gmail.com> Co-authored-by: Cheng Tang <chenta@microsoft.com@orttrainingdev9.d32nl1ml4oruzj4qz3bqlggovf.px.internal.cloudapp.net> Co-authored-by: Cheng Tang <chenta@microsoft.com> Co-authored-by: Jeff Daily <jeff.daily@amd.com> Co-authored-by: cloudhan <cloudhan@outlook.com> Co-authored-by: Yufeng Li <liyufeng1987@gmail.com> Co-authored-by: Zhang Lei <zhang.huanning@hotmail.com> Co-authored-by: Dwayne Robinson <fdwr@hotmail.com> Co-authored-by: Zhipeng Han <zhipeng.han@outlook.com> Co-authored-by: Thiago Crepaldi <thiago.crepaldi@microsoft.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Patrice Vignola <vignola.patrice@gmail.com> Co-authored-by: kunal-vaishnavi <115581922+kunal-vaishnavi@users.noreply.github.com> Co-authored-by: snadampal <87143774+snadampal@users.noreply.github.com> Co-authored-by: Sumit Agarwal <sumitagarwal330@gmail.com> Co-authored-by: Ashwini Khade <askhade@microsoft.com> Co-authored-by: Yang Gu <yang.gu@intel.com> Co-authored-by: Cheng Tang <chenta@a100.crj0ad2y1kku1j4yxl4sj10o4e.gx.internal.cloudapp.net> Co-authored-by: mindest <30493312+mindest@users.noreply.github.com> Co-authored-by: Scott McKay <Scott.McKay@microsoft.com> Co-authored-by: Xavier Dupre <xadupre@microsoft.com@orttrainingdev9.d32nl1ml4oruzj4qz3bqlggovf.px.internal.cloudapp.net> Co-authored-by: guyang3532 <62738430+guyang3532@users.noreply.github.com> Co-authored-by: Carson M <carson@pyke.io> Co-authored-by: sophies927 <107952697+sophies927@users.noreply.github.com>
227 lines
7.7 KiB
Python
227 lines
7.7 KiB
Python
# Copyright (c) Microsoft Corporation. All rights reserved.
|
|
# Licensed under the MIT License.
|
|
|
|
import collections
|
|
import contextlib
|
|
import datetime
|
|
import os
|
|
import shutil
|
|
import signal
|
|
import subprocess
|
|
import time
|
|
import typing
|
|
|
|
from ..logger import get_logger
|
|
from ..platform_helpers import is_linux, is_windows
|
|
from ..run import run
|
|
|
|
_log = get_logger("util.android")
|
|
|
|
|
|
SdkToolPaths = collections.namedtuple("SdkToolPaths", ["emulator", "adb", "sdkmanager", "avdmanager"])
|
|
|
|
|
|
def get_sdk_tool_paths(sdk_root: str):
|
|
def filename(name, windows_extension):
|
|
if is_windows():
|
|
return f"{name}.{windows_extension}"
|
|
else:
|
|
return name
|
|
|
|
def resolve_path(dirnames, basename):
|
|
dirnames.insert(0, "")
|
|
for dirname in dirnames:
|
|
path = shutil.which(os.path.join(os.path.expanduser(dirname), basename))
|
|
if path is not None:
|
|
path = os.path.realpath(path)
|
|
_log.debug(f"Found {basename} at {path}")
|
|
return path
|
|
raise FileNotFoundError(f"Failed to resolve path for {basename}")
|
|
|
|
return SdkToolPaths(
|
|
emulator=resolve_path([os.path.join(sdk_root, "emulator")], filename("emulator", "exe")),
|
|
adb=resolve_path([os.path.join(sdk_root, "platform-tools")], filename("adb", "exe")),
|
|
sdkmanager=resolve_path(
|
|
[os.path.join(sdk_root, "cmdline-tools", "latest", "bin")],
|
|
filename("sdkmanager", "bat"),
|
|
),
|
|
avdmanager=resolve_path(
|
|
[os.path.join(sdk_root, "cmdline-tools", "latest", "bin")],
|
|
filename("avdmanager", "bat"),
|
|
),
|
|
)
|
|
|
|
|
|
def create_virtual_device(sdk_tool_paths: SdkToolPaths, system_image_package_name: str, avd_name: str):
|
|
run(sdk_tool_paths.sdkmanager, "--install", system_image_package_name, input=b"y")
|
|
|
|
run(
|
|
sdk_tool_paths.avdmanager,
|
|
"create",
|
|
"avd",
|
|
"--name",
|
|
avd_name,
|
|
"--package",
|
|
system_image_package_name,
|
|
"--force",
|
|
input=b"no",
|
|
)
|
|
|
|
|
|
_process_creationflags = subprocess.CREATE_NEW_PROCESS_GROUP if is_windows() else 0
|
|
|
|
|
|
def _start_process(*args) -> subprocess.Popen:
|
|
_log.debug(f"Starting process - args: {[*args]}")
|
|
return subprocess.Popen([*args], creationflags=_process_creationflags)
|
|
|
|
|
|
_stop_signal = signal.CTRL_BREAK_EVENT if is_windows() else signal.SIGTERM
|
|
|
|
|
|
def _stop_process(proc: subprocess.Popen):
|
|
if proc.returncode is not None:
|
|
# process has exited
|
|
return
|
|
|
|
_log.debug(f"Stopping process - args: {proc.args}")
|
|
proc.send_signal(_stop_signal)
|
|
|
|
try:
|
|
proc.wait(30)
|
|
except subprocess.TimeoutExpired:
|
|
_log.warning("Timeout expired, forcibly stopping process...")
|
|
proc.kill()
|
|
|
|
|
|
def _stop_process_with_pid(pid: int):
|
|
# minimize scope of external module usage
|
|
import psutil
|
|
|
|
if psutil.pid_exists(pid):
|
|
process = psutil.Process(pid)
|
|
_log.debug(f"Stopping process - pid={pid}")
|
|
process.terminate()
|
|
try:
|
|
process.wait(60)
|
|
except psutil.TimeoutExpired:
|
|
print("Process did not terminate within 60 seconds. Killing.")
|
|
process.kill()
|
|
time.sleep(10)
|
|
if psutil.pid_exists(pid):
|
|
print(f"Process still exists. State:{process.status()}")
|
|
else:
|
|
_log.debug(f"No process exists with pid={pid}")
|
|
|
|
|
|
def start_emulator(
|
|
sdk_tool_paths: SdkToolPaths, avd_name: str, extra_args: typing.Optional[typing.Sequence[str]] = None
|
|
) -> subprocess.Popen:
|
|
with contextlib.ExitStack() as emulator_stack, contextlib.ExitStack() as waiter_stack:
|
|
emulator_args = [
|
|
sdk_tool_paths.emulator,
|
|
"-avd",
|
|
avd_name,
|
|
"-memory",
|
|
"4096",
|
|
"-timezone",
|
|
"America/Los_Angeles",
|
|
"-no-snapstorage",
|
|
"-no-audio",
|
|
"-no-boot-anim",
|
|
"-gpu",
|
|
"guest",
|
|
"-delay-adb",
|
|
]
|
|
|
|
# For Linux CIs we must use "-no-window" otherwise you'll get
|
|
# Fatal: This application failed to start because no Qt platform plugin could be initialized
|
|
#
|
|
# For macOS CIs use a window so that we can potentially capture the desktop and the emulator screen
|
|
# and publish screenshot.jpg and emulator.png as artifacts to debug issues.
|
|
# screencapture screenshot.jpg
|
|
# $(ANDROID_SDK_HOME)/platform-tools/adb exec-out screencap -p > emulator.png
|
|
#
|
|
# On Windows it doesn't matter (AFAIK) so allow a window which is nicer for local debugging.
|
|
if is_linux():
|
|
emulator_args.append("-no-window")
|
|
|
|
if extra_args is not None:
|
|
emulator_args += extra_args
|
|
|
|
emulator_process = emulator_stack.enter_context(_start_process(*emulator_args))
|
|
emulator_stack.callback(_stop_process, emulator_process)
|
|
|
|
# we're specifying -delay-adb so use a trivial command to check when adb is available.
|
|
waiter_process = waiter_stack.enter_context(
|
|
_start_process(
|
|
sdk_tool_paths.adb,
|
|
"wait-for-device",
|
|
"shell",
|
|
"ls /data/local/tmp",
|
|
)
|
|
)
|
|
|
|
waiter_stack.callback(_stop_process, waiter_process)
|
|
|
|
# poll subprocesses.
|
|
# allow 20 minutes for startup as some CIs are slow. TODO: Make timeout configurable if needed.
|
|
sleep_interval_seconds = 10
|
|
end_time = datetime.datetime.now() + datetime.timedelta(minutes=20)
|
|
|
|
while True:
|
|
waiter_ret, emulator_ret = waiter_process.poll(), emulator_process.poll()
|
|
|
|
if emulator_ret is not None:
|
|
# emulator exited early
|
|
raise RuntimeError(f"Emulator exited early with return code: {emulator_ret}")
|
|
|
|
if waiter_ret is not None:
|
|
if waiter_ret == 0:
|
|
_log.debug("adb wait-for-device process has completed.")
|
|
break
|
|
raise RuntimeError(f"Waiter process exited with return code: {waiter_ret}")
|
|
|
|
if datetime.datetime.now() > end_time:
|
|
raise RuntimeError("Emulator startup timeout")
|
|
|
|
time.sleep(sleep_interval_seconds)
|
|
|
|
# emulator is started
|
|
emulator_stack.pop_all()
|
|
|
|
# loop to check for sys.boot_completed being set.
|
|
# in theory `-delay-adb` should be enough but this extra check seems to be required to be sure.
|
|
while True:
|
|
# looping on device with `while` seems to be flaky so loop here and call getprop once
|
|
args = [
|
|
sdk_tool_paths.adb,
|
|
"shell",
|
|
# "while [[ -z $(getprop sys.boot_completed) | tr -d '\r' ]]; do sleep 5; done; input keyevent 82",
|
|
"getprop sys.boot_completed",
|
|
]
|
|
|
|
_log.debug(f"Starting process - args: {args}")
|
|
|
|
getprop_output = subprocess.check_output(args, timeout=10)
|
|
getprop_value = bytes.decode(getprop_output).strip()
|
|
|
|
if getprop_value == "1":
|
|
break
|
|
|
|
elif datetime.datetime.now() > end_time:
|
|
raise RuntimeError("Emulator startup timeout. sys.boot_completed was not set.")
|
|
|
|
_log.debug(f"sys.boot_completed='{getprop_value}'. Sleeping for {sleep_interval_seconds} before retrying.")
|
|
time.sleep(sleep_interval_seconds)
|
|
|
|
return emulator_process
|
|
|
|
|
|
def stop_emulator(emulator_proc_or_pid: typing.Union[subprocess.Popen, int]):
|
|
if isinstance(emulator_proc_or_pid, subprocess.Popen):
|
|
_stop_process(emulator_proc_or_pid)
|
|
elif isinstance(emulator_proc_or_pid, int):
|
|
_stop_process_with_pid(emulator_proc_or_pid)
|
|
else:
|
|
raise ValueError("Expected either a PID or subprocess.Popen instance.")
|