File size: 2,106 Bytes
31ffdfe | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | # SPDX-License-Identifier: Apache-2.0
"""The AutoE2E checkpoint as an attribute tree, without the upstream code (no timm): ``load_tree(path)`` returns an
object on which ``tree.Reactive_E2E.FeatureFusion.view_fusion.layers[0].self_attention.value_proj.weight`` is the
state-dict tensor of that name (numeric path segments index: ``layers[0]``, ``ffn[3]``). Enough for
``PortForm`` and the device modules, which read parameters only.
"""
from __future__ import annotations
from typing import Any, Dict
FRONT_CAMERA_INDEX = 0 # view order: front, front_left, front_right, rear_left, rear, rear_right
class Node:
def __init__(self):
self._c: Dict[str, Any] = {}
def __getattr__(self, name: str) -> Any:
c = self.__dict__.get("_c", {})
if name in c:
return c[name]
raise AttributeError(name)
def __getitem__(self, i: Any) -> Any:
return self._c[str(i)]
def __iter__(self):
keys = sorted(self._c, key=lambda k: (not k.isdigit(), int(k) if k.isdigit() else 0, k))
return iter([self._c[k] for k in keys])
def __len__(self) -> int:
return len(self._c)
def tree(state: Dict[str, Any]) -> Node:
root = Node()
for key, value in state.items():
node = root
parts = key.split(".")
for p in parts[:-1]:
node = node._c.setdefault(p, Node())
node._c[parts[-1]] = value
return root
def load_tree(path: str) -> Node:
"""The checkpoint at ``path`` (``weights_only``: tensors only, no pickle execution) as a :class:`Node` tree, with
the constructor constants the parameter tree lacks (``front_camera_index``)."""
import torch
ck = torch.load(path, map_location="cpu", weights_only=True)
root = tree({k: v.float() if v.is_floating_point() else v for k, v in ck["model_state_dict"].items()})
root.Reactive_E2E.FeatureFusion.view_fusion._c["front_camera_index"] = FRONT_CAMERA_INDEX
layers = root.Reactive_E2E.FeatureFusion.view_fusion.layers
root.Reactive_E2E.FeatureFusion.view_fusion._c["layers"] = list(layers)
return root
|