Compare commits

..

13 Commits

Author SHA1 Message Date
royjr d44645fc53 Revert "simple for now"
This reverts commit 01420fc08488374ec8fe3d17b757ccd1564d1328.
2026-08-30 22:02:01 -04:00
royjr 2f2692d515 Revert "ignore for now"
This reverts commit f571b2b9201f0a7a5571d3114a317bd9e55d879b.
2026-08-30 22:02:01 -04:00
royjr d7aa0f5002 ignore for now 2026-08-30 22:02:01 -04:00
royjr a763c93496 simple for now 2026-08-30 22:02:01 -04:00
royjr cf0c41af96 AuxPowerSave 2026-08-30 22:02:01 -04:00
royjr 34e35d49e1 Revert "do we need this"
This reverts commit 1daecafee4.
2026-08-30 22:02:01 -04:00
royjr a5ec1b3f16 do we need this 2026-08-30 22:02:01 -04:00
royjr b7c40b4c44 fix ui 2026-08-30 22:02:01 -04:00
royjr 4033119fa0 Revert "ignition"
This reverts commit 304df24970.
2026-08-30 22:02:01 -04:00
royjr 7bb32de4b8 ignition 2026-08-30 22:02:01 -04:00
royjr 7419b2a0b0 perms 2026-08-30 22:02:01 -04:00
royjr aa8a190f5a try this 2026-08-30 22:02:01 -04:00
royjr de197ba6fa chestnut: alert when big model ready (#1947)
egpu: alert when big model ready

Co-authored-by: Jason Wen <haibin.wen3@gmail.com>
2026-08-30 16:20:16 -04:00
14 changed files with 69 additions and 199 deletions
+1
View File
@@ -353,6 +353,7 @@ struct OnroadEventSP @0xda96579883444c35 {
speedLimitPending @22;
e2eChime @23;
laneChangeRoadEdge @24;
bigModelReady @25;
}
}
+1
View File
@@ -132,6 +132,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"UptimeOnroad", {PERSISTENT, FLOAT, "0.0"}},
{"ChestnutActive", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION | CLEAR_ON_IGNITION_ON, BOOL}},
{"ChestnutLoading", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION | CLEAR_ON_IGNITION_ON, BOOL}},
{"AuxPowerSave", {PERSISTENT | BACKUP, BOOL}},
{"Version", {PERSISTENT, STRING}},
// --- sunnypilot params --- //
@@ -198,6 +198,7 @@ class SelfdriveD(CruiseHelper):
loading = self.params.get_bool("ChestnutLoading")
if self.big_model_loading and not loading:
self.big_model_ready_t = time.monotonic()
self.events_sp.add(custom.OnroadEventSP.EventName.bigModelReady)
self.big_model_loading = loading
if self.big_model_loading:
self.events.add(EventName.bigModelLoading)
+1
View File
@@ -220,6 +220,7 @@ class UIState(UIStateSP):
ChestnutState.UNCOMPILED if detected else ChestnutState.DISCONNECTED)
return
self.chestnut_present = self.chestnut_present or detected
model_seen = self.sm.recv_frame["modelV2"] > self.started_frame
if not self.chestnut_present:
self.chestnut_state = ChestnutState.DISCONNECTED
+29 -43
View File
@@ -8,22 +8,22 @@ See the LICENSE.md file in the root directory for more details.
import os
os.environ['GMMU'] = '0'
import numpy as np
import threading
import time
from setproctitle import setproctitle
from tinygrad.tensor import Tensor
import openpilot.cereal.messaging as messaging
from openpilot.common.hardware import COMMA_HARDWARE
from openpilot.selfdrive.modeld.helpers import chestnut_present, load_oob
import time
import numpy as np
import openpilot.cereal.messaging as messaging
from openpilot.cereal import log
from opendbc.car.structs import car
from openpilot.cereal.services import SERVICE_LIST
from setproctitle import setproctitle
from openpilot.cereal.messaging import PubMaster, SubMaster
from openpilot.cereal.visionipc import VisionStreamType
from msgq.visionipc import VisionIpcClient, VisionBuf
from opendbc.car.car_helpers import get_demo_car_params
from tinygrad.tensor import Tensor
from openpilot.common.file_chunker import open_file_chunked
from openpilot.common.swaglog import cloudlog
from openpilot.common.params import Params
@@ -42,13 +42,13 @@ from openpilot.sunnypilot.modeld_v2.constants import Plan
from openpilot.sunnypilot.modeld_v2.meta_helper import load_meta_constants
from openpilot.sunnypilot.modeld_v2.camera_offset_helper import CameraOffsetHelper
from openpilot.sunnypilot.modeld_v2.compile_modeld import derive_frame_skip, make_split_input_queues, make_supercombo_input_queues, WARP_INPUTS, POLICY_INPUTS
from openpilot.sunnypilot.livedelay.helpers import get_lat_delay
from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase
from openpilot.sunnypilot.models.helpers import get_active_bundle
from openpilot.sunnypilot.selfdrive.controls.lib.relc import RoadEdgeLaneChangeController
PROCESS_NAME = "openpilot.selfdrive.modeld.modeld_tinygrad"
BIG_MODEL_TIMEOUT = 60
def _pkl_exists(path):
@@ -68,7 +68,6 @@ def _find_driving_pkl(bundle):
pkl_path = os.path.join(model_root, pkl_name)
if _pkl_exists(pkl_path):
return pkl_path
return None
class FrameMeta:
@@ -103,7 +102,7 @@ class ModelState(ModelStateBase):
self.chestnut = chestnut
pkl_path = _find_driving_pkl(model_bundle)
assert pkl_path is not None, f"No driving pkl found for {'chestnut' if chestnut else 'small model'} — all models must be compiled with compile_modeld.py"
assert pkl_path is not None, "No driving pkl found — all models must be compiled with compile_modeld.py"
self._init_combined(pkl_path, cam_w, cam_h, model_bundle)
def _init_combined(self, pkl_path, cam_w, cam_h, bundle):
@@ -186,6 +185,9 @@ class ModelState(ModelStateBase):
else:
self.warp(**{k: self.input_queues[k] for k in WARP_INPUTS}, frame=frame_tensor, big_frame=big_frame_tensor)
if self.chestnut:
self.warmup()
def warmup(self) -> None:
dummy_frames = {k: np.zeros(self.frame_buf_params[k][3], dtype=np.uint8) for k in self._vision_input_names}
transforms = {k: np.eye(3, dtype=np.float32) for k in [self._road_key, self._wide_key] if k}
@@ -286,7 +288,8 @@ class ModelState(ModelStateBase):
buf[0, -1, :] = outputs['desired_curvature'][0, :] if not self.mlsim else 0
if self.chestnut and not np.all(np.isfinite(outputs.get('plan', np.array([0.])))):
raise RuntimeError("model output not finite")
cloudlog.error("model output not finite, dropping frame")
return None
return outputs
@@ -360,26 +363,21 @@ def main(demo=False):
model = None
if CHESTNUT:
big_model = None
def load_big():
nonlocal big_model
try:
m = ModelState(cam_w=vipc_client_main.width, cam_h=vipc_client_main.height, chestnut=True)
m.warmup()
big_model = m
except Exception:
cloudlog.exception("chestnut load failed")
loader = threading.Thread(target=load_big, daemon=True)
loader.start()
loader.join(BIG_MODEL_TIMEOUT)
model = big_model
params.put_bool("ChestnutActive", model is not None)
import threading
def load():
nonlocal model
model = ModelState(cam_w=vipc_client_main.width, cam_h=vipc_client_main.height, chestnut=True)
t = threading.Thread(target=load, daemon=True)
t.start()
t.join(60)
if model is None:
params.put_bool("ChestnutActive", False)
raise RuntimeError("chestnut model load failed or timed out (60s)")
params.put_bool("ChestnutActive", True)
else:
model = ModelState(cam_w=vipc_client_main.width, cam_h=vipc_client_main.height, chestnut=False)
small_model = ModelState(cam_w=vipc_client_main.width, cam_h=vipc_client_main.height, chestnut=False) if model is None or CHESTNUT else None
if model is None:
model = small_model
params.put_bool("ChestnutLoading", False)
assert model is not None
cloudlog.warning(f"models loaded in {time.monotonic() - st:.1f}s, modeld starting")
# messaging
@@ -388,7 +386,7 @@ def main(demo=False):
sm = SubMaster(["deviceState", "carState", "narrowRoadCameraState", "extrinsicsCalibration", "driverMonitoringState", "carControl", "lateralDelay"])
publish_state = PublishState()
chestnut_state = ChestnutState(pm, model.chestnut) if CHESTNUT else None
chestnut_state = ChestnutState(pm, CHESTNUT) if CHESTNUT else None
# setup filter to track dropped frames
frame_dropped_filter = FirstOrderFilter(0., 10., 1. / model.constants.MODEL_FREQ)
@@ -511,19 +509,7 @@ def main(demo=False):
inputs['action_t'] = np.array([lat_action_t, long_action_t], dtype=np.float32)
mt1 = time.perf_counter()
try:
model_output = model.run(bufs, transforms, inputs, prepare_only)
except Exception:
if not params.get_bool("ChestnutActive"):
raise
cloudlog.exception("chestnut failed, falling back to small")
params.put_bool("ChestnutActive", False)
assert small_model is not None
model = small_model
if chestnut_state is not None:
chestnut_state.big = False
run_count = 0
model_output = None
model_output = model.run(bufs, transforms, inputs, prepare_only)
mt2 = time.perf_counter()
model_execution_time = mt2 - mt1
@@ -37,7 +37,7 @@ class DummyModel:
class DummyBundle:
def __init__(self, is_20hz=False, models=None, generation=10, is_big=False):
def __init__(self, is_20hz=False, models=None, generation=10):
self.overrides = [DummyOverride('lat', '.1'), DummyOverride('long', '.3')]
self.generation = generation
self.is20hz = is_20hz
@@ -1,127 +0,0 @@
import io
import requests
from unittest import mock
from openpilot.common.file_chunker import get_chunk_name
from openpilot.common.hardware import hw
from openpilot.common.test import OpenpilotTestCase
from openpilot.selfdrive.modeld.helpers import dump_oob
import openpilot.sunnypilot.modeld_v2.modeld as modeld_module
from openpilot.sunnypilot.modeld_v2.tests import helpers as tests_helpers
from openpilot.sunnypilot.modeld_v2.tests.helpers import DummyModel, DummyBundle, CAM_W, CAM_H
from openpilot.sunnypilot.models.fetcher import ModelParser, ModelFetcher
tmp_path = tests_helpers.tmp_path
class TestFallback(OpenpilotTestCase):
def test_find_dual_model_in_bundle(self, tmp_path, monkeypatch):
lebowski_file = 'driving_lebowski.pkl'
tsfdo_file = 'driving_tsfdo.pkl'
(tmp_path / lebowski_file).write_bytes(b'fkasdjfkljf')
(tmp_path / tsfdo_file).write_bytes(b'dskfajklsdjlsfka')
monkeypatch.setattr(hw.Paths, 'model_root', staticmethod(lambda: str(tmp_path)))
big_bundle = DummyBundle(models=[DummyModel('supercombo', lebowski_file)], is_big=True)
small_bundle = DummyBundle(models=[DummyModel('supercombo', tsfdo_file)], is_big=False)
big_pkl = modeld_module._find_driving_pkl(big_bundle)
small_pkl = modeld_module._find_driving_pkl(small_bundle)
assert big_pkl is not None and lebowski_file in big_pkl
assert small_pkl is not None and tsfdo_file in small_pkl
def test_download_models_and_init_modelstate_fallback(self, tmp_path, monkeypatch):
monkeypatch.setattr(hw.Paths, 'model_root', staticmethod(lambda: str(tmp_path)))
big_json = requests.get(ModelFetcher.MODEL_URL_CHESTNUT).json()
big_bundle = ModelParser.parse_models(big_json)[-1]
small_json = requests.get(ModelFetcher.MODEL_URL).json()
small_bundle = ModelParser.parse_models(small_json)[-1]
buf = io.BytesIO()
dump_oob(tests_helpers.make_pkl_data(tests_helpers.ARCHETYPES['supercombo_non20hz']), buf)
oob_bytes = buf.getvalue()
for bundle in (big_bundle, small_bundle):
artifact = bundle.models[0].artifact
for i in range(len(artifact.chunks)):
(tmp_path / get_chunk_name(artifact.fileName, i, len(artifact.chunks))).write_bytes(oob_bytes if i == 0 else b"")
monkeypatch.setattr(modeld_module, 'get_active_bundle', lambda params=None, *, chestnut=None: small_bundle)
assert modeld_module.ModelState(CAM_W, CAM_H, chestnut=False).chestnut is False
monkeypatch.setattr(modeld_module, 'get_active_bundle', lambda params=None, *, chestnut=None: big_bundle)
try:
assert modeld_module.ModelState(CAM_W, CAM_H, chestnut=True).chestnut is True
except Exception as e:
assert "AMD" in str(e) or "device" in str(e).lower()
def test_runtime_fallback_from_big_to_small(self):
params = mock.MagicMock()
params.get_bool.return_value = True
big = mock.MagicMock(chestnut=True)
big.run.side_effect = RuntimeError("eGPU error")
small = mock.MagicMock(chestnut=False)
small.run.return_value = {"plan": []}
chestnut = mock.MagicMock(big=True)
model, run_count = big, 50
try:
model.run()
except Exception:
if not params.get_bool("chestnutActive"):
raise
params.put_bool("chestnutActive", False)
model = small
chestnut.big = False
run_count = 0
assert model is small
assert not chestnut.big
assert run_count == 0
params.put_bool.assert_called_with("chestnutActive", False)
model.run()
small.run.assert_called_once()
def test_runtime_stays_on_big_model_if_no_errors(self):
params = mock.MagicMock()
params.get_bool.return_value = True
big = mock.MagicMock(chestnut=True)
big.run.return_value = {"plan": [1, 2, 3]}
small = mock.MagicMock(chestnut=False)
chestnut = mock.MagicMock(big=True)
model, run_count = big, 50
try:
model.run()
except Exception:
if not params.get_bool("ChestnutActive"):
raise
params.put_bool("ChestnutActive", False)
model = small
chestnut.big = False
run_count = 0
assert model is big
assert chestnut.big is True
assert run_count == 50
params.put_bool.assert_not_called()
small.run.assert_not_called()
def test_runtime_exception_on_small_model_raises(self):
params = mock.MagicMock()
params.get_bool.return_value = False
model = mock.MagicMock(chestnut=False)
model.run.side_effect = RuntimeError("CPU error")
with self.assertRaises(RuntimeError):
try:
model.run()
except Exception:
if not params.get_bool("ChestnutActive"):
raise
+2 -20
View File
@@ -1,14 +1,11 @@
import argparse
import os
import hashlib
import requests
import re
from openpilot.common.basedir import BASEDIR
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.sunnypilot import get_file_hash
from openpilot.sunnypilot.models.model_name import DEFAULT_MODEL, DEFAULT_BIG_MODEL
from openpilot.sunnypilot.models.fetcher import ModelFetcher
def get_default_model() -> str:
@@ -33,29 +30,14 @@ def update_model_hash():
print(f"Generated and updated new combined model hash to {MODEL_HASH_PATH}")
def get_ref_for_name(url: str, name: str) -> str:
response = requests.get(url, timeout=10)
if response.status_code == 200:
bundles = response.json()["bundles"]
matching = [b for b in bundles if re.search(name, f"{b['short_name']} {b['display_name']}", re.IGNORECASE)]
if matching:
return max(matching, key=lambda b: int(b["index"]))["ref"]
return ""
def update_default_model_names(default_model_name: str, default_big_model_name: str):
print("[CHANGE DEFAULT MODEL NAMES]")
small_ref = get_ref_for_name(ModelFetcher.MODEL_URL, default_model_name)
big_ref = get_ref_for_name(ModelFetcher.MODEL_URL_CHESTNUT, default_big_model_name)
with open(DEFAULT_MODEL_NAME_PATH, "w") as f:
f.write(f'DEFAULT_MODEL = "{default_model_name}"\n')
f.write(f'DEFAULT_MODEL_REF = "{small_ref}"\n')
f.write(f'DEFAULT_BIG_MODEL = "{default_big_model_name}"\n')
f.write(f'DEFAULT_BIG_MODEL_REF = "{big_ref}"\n')
print(f'New default small model name: "{default_model_name}" (ref: {small_ref})')
print(f'New default big model name: "{default_big_model_name}" (ref: {big_ref})')
print(f'New default small model name: "{default_model_name}"')
print(f'New default big model name: "{default_big_model_name}"')
print("[DONE]")
-6
View File
@@ -328,12 +328,6 @@ class ModelManagerSP:
validate_active_bundles(self.params, self.source_models)
self.active_bundle = get_active_bundle(self.params, chestnut=self.chestnut_present)
if get_selected_bundle(self.params, "chestnut") is not None and get_selected_bundle(self.params, "qcom") is None:
if self.params.get("ModelManager_DownloadRef") is None:
from openpilot.sunnypilot.models.model_name import DEFAULT_MODEL_REF
if DEFAULT_MODEL_REF:
self.params.put("ModelManager_DownloadRef", DEFAULT_MODEL_REF)
self._process_download_requests()
if self.params.get("ModelManager_ClearCache"):
@@ -1,4 +1,2 @@
DEFAULT_MODEL = "CD210"
DEFAULT_MODEL_REF = "5b6436a90cf6902b8aaa71c2b6f3d7164d8ae391"
DEFAULT_BIG_MODEL = "Lebowski"
DEFAULT_BIG_MODEL_REF = "fa0c6876d3cf070e91e25e5353ceadc68a5b3285"
@@ -252,4 +252,12 @@ EVENTS_SP: dict[int, dict[str, Alert | AlertCallbackType]] = {
AlertStatus.userPrompt, AlertSize.small,
Priority.LOW, VisualAlert.none, AudibleAlert.prompt, 0.1),
},
EventNameSP.bigModelReady: {
ET.PERMANENT: Alert(
"Big Model Ready",
"",
AlertStatus.normal, AlertSize.small,
Priority.LOW, VisualAlert.none, AudibleAlert.prompt, 2.),
},
}
@@ -1675,6 +1675,12 @@
"widget": "toggle",
"title": "Onroad Uploads"
},
{
"key": "AuxPowerSave",
"widget": "toggle",
"title": "Disable Aux Port When Offroad",
"description": "Power off the aux USB-C port while offroad to save power. It powers back on automatically when you go onroad."
},
{
"key": "MaxTimeOffroad",
"widget": "option",
@@ -30,6 +30,10 @@ sections:
- key: OnroadUploads
widget: toggle
title: Onroad Uploads
- key: AuxPowerSave
widget: toggle
title: Disable Aux Port When Offroad
description: Power off the aux USB-C port while offroad to save power. It powers back on automatically when you go onroad.
- key: MaxTimeOffroad
widget: option
title: Max Time Offroad
+15
View File
@@ -21,6 +21,7 @@ from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert
from openpilot.common.hardware import HARDWARE, COMMA_HARDWARE
from openpilot.common.basedir import BASEDIR
from openpilot.common.hardware.usb import CHESTNUT_FW_VERSION, CHESTNUT_ROM_USB_IDS, CHESTNUT_USB_IDS, get_usb_state, get_usb_topology, set_usb_state
from openpilot.system.hardware.chestnut.flash import VBUS_PATH
from openpilot.common.linux import LinuxSystemStats
from openpilot.system.loggerd.config import get_available_percent
from openpilot.common.swaglog import cloudlog
@@ -49,6 +50,10 @@ class Chestnut:
self.attempts = 0
self.last_attempt = 0.
self.flashed = False
self.vbus_on = None
self.params = Params()
self.powersave = False
self.last_offroad = None
def flash(self) -> None:
ret = subprocess.run(["sudo", sys.executable, os.path.join(BASEDIR, "openpilot/system/hardware/chestnut/flash.py"), CHESTNUT_FW_VERSION],
@@ -56,9 +61,19 @@ class Chestnut:
cloudlog.event("chestnut flash done", returncode=ret.returncode, output=ret.stdout[-1000:], error=ret.returncode != 0)
self.flashed = ret.returncode == 0
def set_vbus(self, on: bool) -> None:
if on == self.vbus_on:
return
subprocess.run(["sudo", "tee", VBUS_PATH], input=b"1" if on else b"0", stdout=subprocess.DEVNULL, check=False)
self.vbus_on = on
def update(self, offroad: bool, usb_state: list[dict]) -> None:
mismatch = any((d["vendorId"], d["productId"]) in CHESTNUT_USB_IDS + CHESTNUT_ROM_USB_IDS and
d["product"] != f"custom {CHESTNUT_FW_VERSION}-CLEAN" for d in usb_state)
if offroad != self.last_offroad:
self.powersave = self.params.get_bool("AuxPowerSave")
self.last_offroad = offroad
self.set_vbus((not offroad or mismatch) or not self.powersave)
if not mismatch:
self.flashed = False
return