Agora
QNN
AIoT
Qualcomm
FlashOCC / targets /QCS8550 /FP16 /reference /run_flashocc_split_onboard.py
YakumoAkayi's picture
Agora board builds (Model Farm, verified on real boards)
53de6e8 verified
Raw History Blame Contribute Delete
29.9 kB
import argparse
import concurrent.futures
import json
import os
import sys
import time
from functools import lru_cache
import cv2
import numpy as np
import torch
from pyquaternion import Quaternion
try:
from turbojpeg import TJPF_BGR, TurboJPEG
TURBOJPEG_IMPORT_ERROR = None
except ImportError:
TJPF_BGR = None
TurboJPEG = None
TURBOJPEG_IMPORT_ERROR = sys.exc_info()[1]
try:
from deployment import _image_preprocess_ext
except ImportError:
_image_preprocess_ext = None
sys.path.insert(0, os.getcwd())
from deployment.bev_pool_v2_cpu import (
BEVPoolV2Workspace,
bev_pool_v2_cpu,
has_cpp_prepare_backend,
voxel_pooling_prepare_v2_cpp,
)
from deployment.postprocess_flashocc_qnn import logits_to_occ_labels, vis_occ
DATA_CONFIG = {
'cams': [
'CAM_FRONT_LEFT', 'CAM_FRONT', 'CAM_FRONT_RIGHT',
'CAM_BACK_LEFT', 'CAM_BACK', 'CAM_BACK_RIGHT'
],
'Ncams': 6,
'input_size': (256, 704),
'src_size': (900, 1600),
'resize': (-0.06, 0.11),
'rot': (-5.4, 5.4),
'flip': True,
'crop_h': (0.0, 0.0),
'resize_test': 0.0,
}
GRID_CONFIG = {
'x': [-40, 40, 0.4],
'y': [-40, 40, 0.4],
'z': [-1, 5.4, 6.4],
'depth': [1.0, 45.0, 0.5],
}
IMG_MEAN = np.array([123.675, 116.28, 103.53], dtype=np.float32)
IMG_STD = np.array([58.395, 57.12, 57.375], dtype=np.float32)
TO_RGB = True
BEV_OUT_CHANNELS = 64
DOWNSAMPLE = 16
def parse_args():
parser = argparse.ArgumentParser(
description='Run split FlashOCC inference from data_predict without mmcv/mmdet3d dependencies')
parser.add_argument(
'--predict-root',
required=True,
help='directory containing v1.0-mini metadata and samples/CAM_* images')
parser.add_argument(
'--target-image',
required=True,
help='target image filename used to resolve the parent sample token')
parser.add_argument(
'--backend',
choices=['stub', 'onnxruntime'],
default='stub',
help='execution backend for part1/part3; replace stub with your QNN SDK calls on board')
parser.add_argument('--part1-model', default=None, help='path to part1 model file for onnxruntime debug mode')
parser.add_argument('--part3-model', default=None, help='path to part3 model file for onnxruntime debug mode')
parser.add_argument(
'--image-backend',
choices=['auto', 'cv2', 'turbojpeg'],
default='cv2',
help='jpeg decode backend for camera images; auto prefers turbojpeg when available')
parser.add_argument(
'--preprocess-backend',
choices=['auto', 'python', 'process', 'cpp'],
default='cpp',
help='image preprocessing backend; auto prefers cpp, then process, then python')
parser.add_argument('--save-dir', default=None, help='optional directory to save final png/json only')
parser.add_argument('--dump-logits', action='store_true', help='save output_0.npy to save-dir or current directory')
parser.add_argument('--verbose', action='store_true', help='print detailed per-stage logs')
return parser.parse_args()
def load_json(path):
with open(path, 'r', encoding='utf-8') as handle:
return json.load(handle)
@lru_cache(maxsize=4)
def load_predict_metadata(meta_root):
sample_data = load_json(os.path.join(meta_root, 'sample_data.json'))
calibrated_sensor = build_token_index(load_json(os.path.join(meta_root, 'calibrated_sensor.json')))
ego_pose = build_token_index(load_json(os.path.join(meta_root, 'ego_pose.json')))
sensor = build_token_index(load_json(os.path.join(meta_root, 'sensor.json')))
return sample_data, calibrated_sensor, ego_pose, sensor
def build_token_index(items):
return {item['token']: item for item in items}
def resolve_existing_path(root_dir, relative_path):
candidate = os.path.join(root_dir, relative_path)
if os.path.exists(candidate):
return candidate
basename = os.path.basename(relative_path)
for base_dir in ['samples', 'sweeps', '.']:
base_path = os.path.join(root_dir, base_dir)
if not os.path.isdir(base_path):
continue
for current_root, _, files in os.walk(base_path):
if basename in files:
return os.path.join(current_root, basename)
return candidate
def normalize_image(img):
array = np.asarray(img, dtype=np.float32)
if TO_RGB:
array = array[..., ::-1]
array = (array - IMG_MEAN) / IMG_STD
return np.ascontiguousarray(array)
@lru_cache(maxsize=1)
def get_turbojpeg_decoder():
if TurboJPEG is None:
return None
try:
return TurboJPEG()
except Exception:
get_turbojpeg_decoder.last_error = sys.exc_info()[1]
return None
get_turbojpeg_decoder.last_error = None
def resolve_image_backend(image_backend):
if image_backend == 'cv2':
return 'cv2', None
decoder = get_turbojpeg_decoder()
if decoder is not None:
return 'turbojpeg', decoder
if image_backend == 'turbojpeg':
if TURBOJPEG_IMPORT_ERROR is not None:
raise RuntimeError(
'turbojpeg backend requested, but importing turbojpeg failed: '
f'{TURBOJPEG_IMPORT_ERROR}. Install PyTurboJPEG into the same Python environment used to run this script.'
)
if get_turbojpeg_decoder.last_error is not None:
decoder_error = str(get_turbojpeg_decoder.last_error)
if 'requires libjpeg-turbo 3.0 or later' in decoder_error:
raise RuntimeError(
'turbojpeg backend requested, but creating TurboJPEG() failed: '
f'{decoder_error}. Your board currently has libjpeg-turbo 2.x; use PyTurboJPEG<2, '
'or upgrade the system libjpeg-turbo to 3.x before using PyTurboJPEG 2.x.'
)
raise RuntimeError(
'turbojpeg backend requested, but creating TurboJPEG() failed: '
f'{get_turbojpeg_decoder.last_error}. This usually means libturbojpeg is missing or not visible to the loader.'
)
raise RuntimeError('turbojpeg backend requested, but PyTurboJPEG or libturbojpeg is unavailable')
return 'cv2', None
def load_camera_image(image_path, backend, turbojpeg_decoder=None):
if backend == 'turbojpeg':
with open(image_path, 'rb') as handle:
encoded = handle.read()
image = turbojpeg_decoder.decode(encoded, pixel_format=TJPF_BGR)
else:
image = cv2.imread(image_path, cv2.IMREAD_COLOR)
if image is None:
raise FileNotFoundError(f'failed to read image: {image_path}')
return image
def has_cpp_preprocess_backend():
return _image_preprocess_ext is not None
def resolve_preprocess_backend(preprocess_backend):
if preprocess_backend == 'python':
return 'python'
if preprocess_backend == 'process':
return 'process'
if preprocess_backend == 'cpp':
if not has_cpp_preprocess_backend():
raise RuntimeError(
'cpp preprocess backend requested, but deployment/_image_preprocess_ext is unavailable. '
'Build it first with: cd deployment && python setup_image_preprocess_ext.py build_ext --inplace'
)
return 'cpp'
if has_cpp_preprocess_backend():
return 'cpp'
if (os.cpu_count() or 1) > 1:
return 'process'
return 'python'
def load_and_preprocess_one_image(image_path, image_backend):
resolved_image_backend, turbojpeg_decoder = resolve_image_backend(image_backend)
image = load_camera_image(image_path, resolved_image_backend, turbojpeg_decoder)
resize, resize_dims, crop, flip, rotate = sample_test_augmentation(image.shape[0], image.shape[1])
image, post_rot, post_tran = transform_image(image, resize, resize_dims, crop, flip, rotate)
return {
'image': normalize_image(image),
'post_rot': post_rot.numpy(),
'post_tran': post_tran.numpy(),
}
def load_and_preprocess_images_process_pool(image_paths, image_backend):
max_workers = min(len(image_paths), max(1, os.cpu_count() or 1))
with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor:
results = list(executor.map(load_and_preprocess_one_image, image_paths, [image_backend] * len(image_paths)))
return results
def sample_test_augmentation(height, width):
final_height, final_width = DATA_CONFIG['input_size']
resize = float(final_width) / float(width) + DATA_CONFIG.get('resize_test', 0.0)
resize_dims = (int(width * resize), int(height * resize))
new_width, new_height = resize_dims
crop_h = int((1 - np.mean(DATA_CONFIG['crop_h'])) * new_height) - final_height
crop_w = int(max(0, new_width - final_width) / 2)
crop = (crop_w, crop_h, crop_w + final_width, crop_h + final_height)
flip = False
rotate = 0.0
return resize, resize_dims, crop, flip, rotate
def get_rot_matrix(angle_radians):
return torch.tensor([
[np.cos(angle_radians), np.sin(angle_radians)],
[-np.sin(angle_radians), np.cos(angle_radians)],
], dtype=torch.float32)
def apply_image_transform(img, resize_dims, crop, flip, rotate):
img = cv2.resize(img, resize_dims, interpolation=cv2.INTER_LINEAR)
crop_w0, crop_h0, crop_w1, crop_h1 = crop
img = img[crop_h0:crop_h1, crop_w0:crop_w1]
if flip:
img = cv2.flip(img, 1)
if rotate:
center = ((img.shape[1] - 1) * 0.5, (img.shape[0] - 1) * 0.5)
matrix = cv2.getRotationMatrix2D(center, rotate, 1.0)
img = cv2.warpAffine(img, matrix, (img.shape[1], img.shape[0]), flags=cv2.INTER_LINEAR)
return img
def compute_post_transform(resize, crop, flip, rotate):
post_rot = torch.eye(2, dtype=torch.float32)
post_tran = torch.zeros(2, dtype=torch.float32)
post_rot *= resize
post_tran -= torch.tensor(crop[:2], dtype=torch.float32)
if flip:
flip_matrix = torch.tensor([[-1, 0], [0, 1]], dtype=torch.float32)
flip_bias = torch.tensor([crop[2] - crop[0], 0], dtype=torch.float32)
post_rot = flip_matrix.matmul(post_rot)
post_tran = flip_matrix.matmul(post_tran) + flip_bias
rotate_matrix = get_rot_matrix(rotate / 180.0 * np.pi)
rotate_bias = torch.tensor([crop[2] - crop[0], crop[3] - crop[1]], dtype=torch.float32) / 2.0
rotate_bias = rotate_matrix.matmul(-rotate_bias) + rotate_bias
post_rot = rotate_matrix.matmul(post_rot)
post_tran = rotate_matrix.matmul(post_tran) + rotate_bias
post_rot3 = torch.eye(3, dtype=torch.float32)
post_tran3 = torch.zeros(3, dtype=torch.float32)
post_rot3[:2, :2] = post_rot
post_tran3[:2] = post_tran
return post_rot3, post_tran3
def transform_image(img, resize, resize_dims, crop, flip, rotate):
img = apply_image_transform(img, resize_dims, crop, flip, rotate)
post_rot3, post_tran3 = compute_post_transform(resize, crop, flip, rotate)
return img, post_rot3, post_tran3
def build_transform_matrix(rotation, translation):
matrix = torch.eye(4, dtype=torch.float32)
matrix[:3, :3] = torch.tensor(Quaternion(rotation).rotation_matrix, dtype=torch.float32)
matrix[:3, 3] = torch.tensor(translation, dtype=torch.float32)
return matrix
@lru_cache(maxsize=1)
def create_frustum(depth_cfg, input_size, downsample):
height_in, width_in = input_size
feat_height, feat_width = height_in // downsample, width_in // downsample
depth = torch.arange(*depth_cfg, dtype=torch.float32).view(-1, 1, 1).expand(-1, feat_height, feat_width)
x_coords = torch.linspace(0, width_in - 1, feat_width, dtype=torch.float32).view(1, 1, feat_width)
x_coords = x_coords.expand(depth.shape[0], feat_height, feat_width)
y_coords = torch.linspace(0, height_in - 1, feat_height, dtype=torch.float32).view(1, feat_height, 1)
y_coords = y_coords.expand(depth.shape[0], feat_height, feat_width)
return torch.stack((x_coords, y_coords, depth), dim=-1)
@lru_cache(maxsize=1)
def create_grid_infos(grid_key):
config = {axis: list(values) for axis, *values in grid_key}
lower_bound = torch.tensor([config[axis][0] for axis in ['x', 'y', 'z']], dtype=torch.float32)
interval = torch.tensor([config[axis][2] for axis in ['x', 'y', 'z']], dtype=torch.float32)
size = torch.tensor([
(config[axis][1] - config[axis][0]) / config[axis][2]
for axis in ['x', 'y', 'z']
], dtype=torch.float32)
return lower_bound, interval, size
def prepare_inputs(imgs, sensor2egos, ego2globals, intrins, post_rots, post_trans, bda):
keyego2global = ego2globals[:, 0, ...].unsqueeze(1)
global2keyego = torch.inverse(keyego2global.double())
sensor2keyegos = global2keyego @ ego2globals.double() @ sensor2egos.double()
return [
imgs,
sensor2keyegos.float(),
ego2globals.float(),
intrins.float(),
post_rots.float(),
post_trans.float(),
bda.float(),
]
def get_ego_coordinates(frustum, sensor2ego, ego2global, cam2imgs, post_rots, post_trans, bda):
batch_size, num_cams, _, _ = sensor2ego.shape
points = frustum.to(sensor2ego) - post_trans.view(batch_size, num_cams, 1, 1, 1, 3)
points = torch.inverse(post_rots).view(batch_size, num_cams, 1, 1, 1, 3, 3).matmul(points.unsqueeze(-1))
points = torch.cat((points[..., :2, :] * points[..., 2:3, :], points[..., 2:3, :]), dim=5)
combine = sensor2ego[:, :, :3, :3].matmul(torch.inverse(cam2imgs))
points = combine.view(batch_size, num_cams, 1, 1, 1, 3, 3).matmul(points).squeeze(-1)
points += sensor2ego[:, :, :3, 3].view(batch_size, num_cams, 1, 1, 1, 3)
points = bda.view(batch_size, 1, 1, 1, 1, 3, 3).matmul(points.unsqueeze(-1)).squeeze(-1)
return points
def voxel_pooling_prepare_v2(coordinates, grid_lower_bound, grid_interval, grid_size):
if coordinates.device.type == 'cpu' and has_cpp_prepare_backend():
ranks_bev, ranks_depth, ranks_feat, interval_starts, interval_lengths = voxel_pooling_prepare_v2_cpp(
coordinates.numpy(),
grid_lower_bound.numpy(),
grid_interval.numpy(),
grid_size.numpy(),
)
return (
torch.from_numpy(ranks_bev),
torch.from_numpy(ranks_depth),
torch.from_numpy(ranks_feat),
torch.from_numpy(interval_starts),
torch.from_numpy(interval_lengths),
)
batch_size, num_cams, depth_bins, feat_height, feat_width, _ = coordinates.shape
num_points = batch_size * num_cams * depth_bins * feat_height * feat_width
ranks_depth = torch.arange(num_points, dtype=torch.int32, device=coordinates.device)
ranks_feat = torch.arange(num_points // depth_bins, dtype=torch.int32, device=coordinates.device)
ranks_feat = ranks_feat.reshape(batch_size, num_cams, 1, feat_height, feat_width)
ranks_feat = ranks_feat.expand(batch_size, num_cams, depth_bins, feat_height, feat_width).reshape(-1)
coordinates = ((coordinates - grid_lower_bound.to(coordinates)) / grid_interval.to(coordinates)).long()
coordinates = coordinates.view(num_points, 3)
batch_idx = torch.arange(batch_size, dtype=torch.long, device=coordinates.device).view(batch_size, 1)
batch_idx = batch_idx.expand(batch_size, num_points // batch_size).reshape(num_points, 1)
coordinates = torch.cat((coordinates, batch_idx), dim=1)
kept = (
(coordinates[:, 0] >= 0) & (coordinates[:, 0] < grid_size[0]) &
(coordinates[:, 1] >= 0) & (coordinates[:, 1] < grid_size[1]) &
(coordinates[:, 2] >= 0) & (coordinates[:, 2] < grid_size[2])
)
if kept.sum() == 0:
raise RuntimeError('no valid points remain inside the BEV grid')
coordinates = coordinates[kept]
ranks_depth = ranks_depth[kept]
ranks_feat = ranks_feat[kept]
ranks_bev = coordinates[:, 3] * (grid_size[2] * grid_size[1] * grid_size[0])
ranks_bev += coordinates[:, 2] * (grid_size[1] * grid_size[0])
ranks_bev += coordinates[:, 1] * grid_size[0] + coordinates[:, 0]
order = ranks_bev.argsort()
ranks_bev = ranks_bev[order]
ranks_depth = ranks_depth[order]
ranks_feat = ranks_feat[order]
kept = torch.ones(ranks_bev.shape[0], dtype=torch.bool, device=ranks_bev.device)
kept[1:] = ranks_bev[1:] != ranks_bev[:-1]
interval_starts = torch.where(kept)[0].int()
interval_lengths = torch.zeros_like(interval_starts)
interval_lengths[:-1] = interval_starts[1:] - interval_starts[:-1]
interval_lengths[-1] = ranks_bev.shape[0] - interval_starts[-1]
return (
ranks_bev.int().contiguous(),
ranks_depth.int().contiguous(),
ranks_feat.int().contiguous(),
interval_starts.int().contiguous(),
interval_lengths.int().contiguous(),
)
def load_sample_from_predict_root(predict_root, target_image):
meta_root = os.path.join(predict_root, 'v1.0-mini')
sample_data, calibrated_sensor, ego_pose, sensor = load_predict_metadata(meta_root)
target_entry = next((item for item in sample_data if item.get('filename', '').endswith(target_image)), None)
if target_entry is None:
raise FileNotFoundError(f'target image not found in sample_data.json: {target_image}')
sample_token = target_entry['sample_token']
keyframe_entries = [
item for item in sample_data
if item.get('sample_token') == sample_token and item.get('is_key_frame')
]
cam_entries = {}
for item in keyframe_entries:
calibrated = calibrated_sensor[item['calibrated_sensor_token']]
sensor_info = sensor[calibrated['sensor_token']]
channel = sensor_info['channel']
if channel.startswith('CAM_'):
cam_entries[channel] = {
'data_path': resolve_existing_path(predict_root, item['filename']),
'cam_intrinsic': calibrated['camera_intrinsic'],
'sensor2ego_rotation': calibrated['rotation'],
'sensor2ego_translation': calibrated['translation'],
'ego2global_rotation': ego_pose[item['ego_pose_token']]['rotation'],
'ego2global_translation': ego_pose[item['ego_pose_token']]['translation'],
}
missing_cams = [cam for cam in DATA_CONFIG['cams'] if cam not in cam_entries]
if missing_cams:
raise ValueError(f'missing camera metadata for sample {sample_token}: {missing_cams}')
for cam_name, cam_info in cam_entries.items():
if not os.path.exists(cam_info['data_path']):
raise FileNotFoundError(f'missing image for {cam_name}: {cam_info["data_path"]}')
return sample_token, cam_entries
def build_sample_inputs_from_predict_root(
predict_root,
target_image,
backend='stub',
image_backend='auto',
preprocess_backend='auto'):
sample_token, cam_entries = load_sample_from_predict_root(predict_root, target_image)
resolved_image_backend, turbojpeg_decoder = resolve_image_backend(image_backend)
resolved_preprocess_backend = resolve_preprocess_backend(preprocess_backend)
imgs_nhwc = []
sensor2egos = []
ego2globals = []
intrins = []
post_rots = []
post_trans = []
cam_names = list(DATA_CONFIG['cams'])
if resolved_preprocess_backend == 'cpp':
src_height, src_width = DATA_CONFIG['src_size']
resize, resize_dims, crop, flip, rotate = sample_test_augmentation(src_height, src_width)
if flip or rotate:
raise RuntimeError('cpp preprocess backend currently supports the test-time no-flip/no-rotate path only')
img_nhwc = _image_preprocess_ext.load_and_preprocess_images(
[cam_entries[cam_name]['data_path'] for cam_name in cam_names],
int(resize_dims[0]),
int(resize_dims[1]),
int(crop[0]),
int(crop[1]),
int(crop[2] - crop[0]),
int(crop[3] - crop[1]),
IMG_MEAN.tolist(),
IMG_STD.tolist(),
bool(TO_RGB),
len(cam_names),
)
shared_post_rot, shared_post_tran = compute_post_transform(resize, crop, flip, rotate)
elif resolved_preprocess_backend == 'process':
process_results = load_and_preprocess_images_process_pool(
[cam_entries[cam_name]['data_path'] for cam_name in cam_names],
image_backend,
)
for cam_name in cam_names:
cam_info = cam_entries[cam_name]
if resolved_preprocess_backend == 'python':
image = load_camera_image(cam_info['data_path'], resolved_image_backend, turbojpeg_decoder)
resize, resize_dims, crop, flip, rotate = sample_test_augmentation(image.shape[0], image.shape[1])
image, post_rot, post_tran = transform_image(image, resize, resize_dims, crop, flip, rotate)
imgs_nhwc.append(normalize_image(image))
elif resolved_preprocess_backend == 'process':
result = process_results[len(imgs_nhwc)]
imgs_nhwc.append(result['image'])
post_rot = torch.from_numpy(result['post_rot']).float()
post_tran = torch.from_numpy(result['post_tran']).float()
else:
post_rot = shared_post_rot
post_tran = shared_post_tran
sensor2egos.append(build_transform_matrix(cam_info['sensor2ego_rotation'], cam_info['sensor2ego_translation']))
ego2globals.append(build_transform_matrix(cam_info['ego2global_rotation'], cam_info['ego2global_translation']))
intrins.append(torch.tensor(cam_info['cam_intrinsic'], dtype=torch.float32))
post_rots.append(post_rot)
post_trans.append(post_tran)
if resolved_preprocess_backend in ('python', 'process'):
img_nhwc = np.ascontiguousarray(np.stack(imgs_nhwc, axis=0).astype(np.float32, copy=False))
img_nchw = np.ascontiguousarray(np.transpose(img_nhwc, (0, 3, 1, 2)))
imgs = torch.from_numpy(img_nchw).unsqueeze(0).contiguous()
sensor2egos = torch.stack(sensor2egos, dim=0).unsqueeze(0).contiguous()
ego2globals = torch.stack(ego2globals, dim=0).unsqueeze(0).contiguous()
intrins = torch.stack(intrins, dim=0).unsqueeze(0).contiguous()
post_rots = torch.stack(post_rots, dim=0).unsqueeze(0).contiguous()
post_trans = torch.stack(post_trans, dim=0).unsqueeze(0).contiguous()
bda = torch.eye(3, dtype=torch.float32).unsqueeze(0).contiguous()
prepared = prepare_inputs(imgs, sensor2egos, ego2globals, intrins, post_rots, post_trans, bda)
frustum = create_frustum(tuple(GRID_CONFIG['depth']), tuple(DATA_CONFIG['input_size']), DOWNSAMPLE)
grid_key = tuple((axis, *GRID_CONFIG[axis]) for axis in ['x', 'y', 'z'])
grid_lower_bound, grid_interval, grid_size = create_grid_infos(grid_key)
coordinates = get_ego_coordinates(frustum, *prepared[1:7])
ranks_bev, ranks_depth, ranks_feat, interval_starts, interval_lengths = voxel_pooling_prepare_v2(
coordinates, grid_lower_bound, grid_interval, grid_size.long())
bev_shape = [1, int(grid_size[1].item()), int(grid_size[0].item()), BEV_OUT_CHANNELS]
return {
'sample_index': None,
'sample_token': sample_token,
'camera_paths': {key: value['data_path'] for key, value in cam_entries.items()},
'image_backend': resolved_image_backend,
'preprocess_backend': resolved_preprocess_backend,
'img_nchw': img_nchw,
'img_nhwc': img_nhwc,
'ranks_bev': ranks_bev.cpu().numpy().astype(np.int32),
'ranks_depth': ranks_depth.cpu().numpy().astype(np.int32),
'ranks_feat': ranks_feat.cpu().numpy().astype(np.int32),
'interval_starts': interval_starts.cpu().numpy().astype(np.int32),
'interval_lengths': interval_lengths.cpu().numpy().astype(np.int32),
'bev_shape': bev_shape,
'source_target_image': target_image,
}
class BaseSplitRunner:
def run_part1(self, img):
raise NotImplementedError()
def run_part3(self, bev_feat):
raise NotImplementedError()
class StubQNNRunner(BaseSplitRunner):
def __init__(self, part1_model=None, part3_model=None, verbose=False):
from part1 import FlashOccPart1
from part3 import FlashOccPart3
self.model_part1 = FlashOccPart1(part1_model, verbose=verbose)
self.model_part_3 = FlashOccPart3(part3_model, verbose=verbose)
def run_part1(self, img):
return self.model_part1(img)
def run_part3(self, bev_feat):
return self.model_part_3(bev_feat)
class OnnxRuntimeRunner(BaseSplitRunner):
def __init__(self, part1_model, part3_model):
if not part1_model or not part3_model:
raise ValueError('onnxruntime backend requires --part1-model and --part3-model')
import onnxruntime as ort
self.part1_session = ort.InferenceSession(part1_model, providers=['CPUExecutionProvider'])
self.part3_session = ort.InferenceSession(part3_model, providers=['CPUExecutionProvider'])
def run_part1(self, img):
tran_feat, depth = self.part1_session.run(None, {'img': img})
return tran_feat.astype(np.float32), depth.astype(np.float32)
def run_part3(self, bev_feat):
output_0 = self.part3_session.run(None, {'bev_feat': bev_feat})[0]
return output_0.astype(np.float32)
def build_runner(args):
if args.backend == 'onnxruntime':
return OnnxRuntimeRunner(args.part1_model, args.part3_model)
return StubQNNRunner(args.part1_model, args.part3_model, verbose=args.verbose)
def summarize_prediction(logits, occ_labels, sample_inputs):
class_hist = np.bincount(occ_labels.reshape(-1), minlength=18)
return {
'sample_index': sample_inputs['sample_index'],
'sample_token': sample_inputs['sample_token'],
'camera_paths': sample_inputs['camera_paths'],
'source_target_image': sample_inputs.get('source_target_image'),
'img_shape': list(sample_inputs['img_nchw'].shape),
'tran_feat_points': int(sample_inputs['ranks_feat'].shape[0]),
'bev_intervals': int(sample_inputs['interval_starts'].shape[0]),
'bev_shape': sample_inputs['bev_shape'],
'output_shape': list(logits.shape),
'predicted_class_histogram': class_hist.tolist(),
}
def maybe_save_outputs(save_dir, summary, occ_bev, logits=None):
if not save_dir:
return
os.makedirs(save_dir, exist_ok=True)
summary_path = os.path.join(save_dir, 'prediction_summary.json')
occ_bev_path = os.path.join(save_dir, 'occ_bev.png')
if logits is not None:
logits_path = os.path.join(save_dir, 'output_0.npy')
np.save(logits_path, logits)
print('saved:', logits_path)
with open(summary_path, 'w', encoding='utf-8') as handle:
json.dump(summary, handle, indent=2, ensure_ascii=False)
cv2.imwrite(occ_bev_path, occ_bev)
print('saved:', summary_path)
print('saved:', occ_bev_path)
def build_bev_pool_workspace(sample_inputs):
return BEVPoolV2Workspace.from_inputs(
ranks_feat=sample_inputs['ranks_feat'],
interval_starts=sample_inputs['interval_starts'],
ranks_bev=sample_inputs['ranks_bev'],
bev_shape=sample_inputs['bev_shape'],
)
def main():
args = parse_args()
stat_time = time.perf_counter()
sample_inputs = build_sample_inputs_from_predict_root(
args.predict_root,
args.target_image,
backend=args.backend,
image_backend=args.image_backend,
preprocess_backend=args.preprocess_backend,
)
print('前处理耗时:', f'{(time.perf_counter() - stat_time) * 1000}ms')
if args.verbose:
print('image backend:', sample_inputs['image_backend'])
print('preprocess backend:', sample_inputs['preprocess_backend'])
bev_workspace = build_bev_pool_workspace(sample_inputs)
runner = build_runner(args)
if args.verbose:
print('Running part1...')
infer_start = time.perf_counter()
part1_input = sample_inputs['img_nhwc'] if args.backend == 'stub' else sample_inputs['img_nchw']
tran_feat, depth = runner.run_part1(part1_input)
if args.verbose:
print('part1 outputs:', list(tran_feat.shape), list(depth.shape))
if args.verbose:
print('Running CPU bev_pool_v2...')
bev_time = time.perf_counter()
bev_feat = bev_pool_v2_cpu(
tran_feat=tran_feat,
depth=depth,
ranks_depth=sample_inputs['ranks_depth'],
ranks_feat=sample_inputs['ranks_feat'],
ranks_bev=sample_inputs['ranks_bev'],
interval_starts=sample_inputs['interval_starts'],
interval_lengths=sample_inputs['interval_lengths'],
bev_shape=sample_inputs['bev_shape'],
workspace=bev_workspace,
).reshape(-1).astype(np.float32, copy=False)
print('bev分析耗时:', f'{(time.perf_counter() - bev_time) * 1000}ms')
if args.verbose:
print('bev_feat shape:', list(bev_feat.shape))
if args.verbose:
print('Running part3...')
logits = runner.run_part3(bev_feat)
print('模型分析总耗时:', f'{(time.perf_counter() - infer_start) * 1000}ms')
print('*' * 50)
print('output shape:', logits.shape)
if args.dump_logits:
output_dir = args.save_dir if args.save_dir else os.getcwd()
if not os.path.exists(output_dir):
os.makedirs(output_dir)
output_path = os.path.join(output_dir, 'output_0.npy')
np.save(output_path, logits)
print('saved:', output_path)
print('*' * 50)
occ_labels = logits_to_occ_labels(logits)
summary = summarize_prediction(logits, occ_labels, sample_inputs)
print(json.dumps(summary, indent=2, ensure_ascii=False))
occ_bev = vis_occ(occ_labels[0]) if args.save_dir else None
maybe_save_outputs(args.save_dir, summary, occ_bev, None)
if __name__ == '__main__':
main()