|
| 1 | +"""This is the model converter to convert a SpConv model to TorchSparse model. |
| 2 | +""" |
| 3 | +import argparse |
| 4 | +import torch |
| 5 | +import re |
| 6 | +import logging |
| 7 | +import spconv.pytorch as spconv |
| 8 | +import logging |
| 9 | + |
| 10 | +# Disable JIT because running OpenPCDet with JIT enabled will cause some import issue. |
| 11 | +torch.jit._state.disable() |
| 12 | + |
| 13 | +# Works for SECOND |
| 14 | +def convert_weights_v2(key, model): |
| 15 | + """Convert model weights for models build with SpConv v2. |
| 16 | +
|
| 17 | + :param key: _description_ |
| 18 | + :type key: _type_ |
| 19 | + :param model: _description_ |
| 20 | + :type model: _type_ |
| 21 | + :return: _description_ |
| 22 | + :rtype: _type_ |
| 23 | + """ |
| 24 | + new_key = key.replace(".weight", ".kernel") |
| 25 | + weights = model[key] |
| 26 | + oc, kx, ky, kz, ic = weights.shape |
| 27 | + |
| 28 | + converted_weights = weights.reshape(oc, -1, ic) |
| 29 | + |
| 30 | + converted_weights = converted_weights.permute(1, 0, 2) |
| 31 | + |
| 32 | + if converted_weights.shape[0] == 1: |
| 33 | + converted_weights = converted_weights[0] |
| 34 | + elif converted_weights.shape[0] == 27: |
| 35 | + offsets = [list(range(kz)), list(range(ky)), list(range(kx))] |
| 36 | + kykx = ky * kx |
| 37 | + offsets = [ |
| 38 | + (x * kykx + y * kx + z) |
| 39 | + for z in offsets[0] |
| 40 | + for y in offsets[1] |
| 41 | + for x in offsets[2] |
| 42 | + ] |
| 43 | + offsets = torch.tensor( |
| 44 | + offsets, dtype=torch.int64, device=converted_weights.device |
| 45 | + ) |
| 46 | + converted_weights = converted_weights[offsets] |
| 47 | + |
| 48 | + converted_weights = converted_weights.permute(0,2,1) |
| 49 | + |
| 50 | + return new_key, converted_weights |
| 51 | + |
| 52 | +# Order for CenterPoint, PV-RCNN, and default, legacy SpConv |
| 53 | +def convert_weights_v1(key, model): |
| 54 | + """Convert model weights for models implemented with SpConv v1 |
| 55 | +
|
| 56 | + :param key: _description_ |
| 57 | + :type key: _type_ |
| 58 | + :param model: _description_ |
| 59 | + :type model: _type_ |
| 60 | + :return: _description_ |
| 61 | + :rtype: _type_ |
| 62 | + """ |
| 63 | + new_key = key.replace(".weight", ".kernel") |
| 64 | + weights = model[key] |
| 65 | + |
| 66 | + kx, ky, kz, ic, oc = weights.shape |
| 67 | + |
| 68 | + converted_weights = weights.reshape(-1, ic, oc) |
| 69 | + if converted_weights.shape[0] == 1: |
| 70 | + converted_weights = converted_weights[0] |
| 71 | + |
| 72 | + elif converted_weights.shape[0] == 27: |
| 73 | + offsets = [list(range(kz)), list(range(ky)), list(range(kx))] |
| 74 | + kykx = ky * kx |
| 75 | + offsets = [ |
| 76 | + (x * kykx + y * kx + z) |
| 77 | + for z in offsets[0] |
| 78 | + for y in offsets[1] |
| 79 | + for x in offsets[2] |
| 80 | + ] |
| 81 | + offsets = torch.tensor( |
| 82 | + offsets, dtype=torch.int64, device=converted_weights.device |
| 83 | + ) |
| 84 | + converted_weights = converted_weights[offsets] |
| 85 | + elif converted_weights.shape[0] == 3: # 3 is the case in PartA2. |
| 86 | + pass |
| 87 | + # offsets = torch.tensor( |
| 88 | + # [2, 1, 0], dtype=torch.int64, device=converted_weights.device |
| 89 | + # ) |
| 90 | + # converted_weights = converted_weights[offsets] |
| 91 | + return new_key, converted_weights |
| 92 | + |
| 93 | +def build_mmdet_model_from_cfg(cfg_path, ckpt_path): |
| 94 | + try: |
| 95 | + from mmdet3d.apis import init_model |
| 96 | + from mmengine.config import Config |
| 97 | + except: |
| 98 | + print("MMDetection3D is not installed. Please install MMDetection3D to use this function.") |
| 99 | + cfg = Config.fromfile(cfg_path) |
| 100 | + model = init_model(cfg, ckpt_path) |
| 101 | + return model |
| 102 | + |
| 103 | +def build_opc_model_from_cfg(cfg_path): |
| 104 | + try: |
| 105 | + from pcdet.config import cfg, cfg_from_yaml_file |
| 106 | + from pcdet.datasets import build_dataloader |
| 107 | + from pcdet.models import build_network |
| 108 | + except Exception as e: |
| 109 | + print(e) |
| 110 | + raise ImportError("Failed to import OpenPCDet") |
| 111 | + cfg_from_yaml_file(cfg_path, cfg) |
| 112 | + test_set, test_loader, sampler = build_dataloader( |
| 113 | + dataset_cfg=cfg.DATA_CONFIG, |
| 114 | + class_names=cfg.CLASS_NAMES, |
| 115 | + batch_size=1, |
| 116 | + dist=False, |
| 117 | + training=False, |
| 118 | + logger=logging.Logger("Build Dataloader"), |
| 119 | + ) |
| 120 | + |
| 121 | + model = build_network(model_cfg=cfg.MODEL, num_class=len(cfg.CLASS_NAMES), dataset=test_set) |
| 122 | + return model |
| 123 | + |
| 124 | +# Allow use the API to convert based on a passed in model. |
| 125 | +def convert_model_weights(ckpt_before, ckpt_after, model, legacy=False): |
| 126 | + |
| 127 | + model_modules = {} |
| 128 | + for key, value in model.named_modules(): |
| 129 | + model_modules[key] = value |
| 130 | + |
| 131 | + cp_old = torch.load(ckpt_before, map_location="cpu") |
| 132 | + try: |
| 133 | + opc = False |
| 134 | + old_state_dict = cp_old["state_dict"] |
| 135 | + except: |
| 136 | + opc = True |
| 137 | + old_state_dict = cp_old["model_state"] |
| 138 | + |
| 139 | + new_model = dict() |
| 140 | + |
| 141 | + for state_dict_key in old_state_dict.keys(): |
| 142 | + is_sparseconv_weight = False |
| 143 | + if state_dict_key.endswith(".weight"): |
| 144 | + if state_dict_key[:-len(".weight")] in model_modules.keys(): |
| 145 | + if isinstance(model_modules[state_dict_key[:-len(".weight")]], (spconv.SparseConv3d, spconv.SubMConv3d, spconv.SparseInverseConv3d)): |
| 146 | + is_sparseconv_weight = True |
| 147 | + |
| 148 | + if is_sparseconv_weight: |
| 149 | + # print(f"{state_dict_key} is a sparseconv weight") |
| 150 | + pass |
| 151 | + |
| 152 | + if is_sparseconv_weight: |
| 153 | + if len(old_state_dict[state_dict_key].shape) == 5: |
| 154 | + if legacy: |
| 155 | + new_key, converted_weights = convert_weights_v1(state_dict_key, old_state_dict) |
| 156 | + else: |
| 157 | + new_key, converted_weights = convert_weights_v2(state_dict_key, old_state_dict) |
| 158 | + else: |
| 159 | + new_key = state_dict_key |
| 160 | + converted_weights = old_state_dict[state_dict_key] |
| 161 | + |
| 162 | + new_model[new_key] = converted_weights |
| 163 | + |
| 164 | + if opc: |
| 165 | + cp_old["model_state"] = new_model |
| 166 | + else: |
| 167 | + cp_old["state_dict"] = new_model |
| 168 | + torch.save(cp_old, ckpt_after) |
| 169 | + |
| 170 | + |
| 171 | +def convert_weights_cmd(): |
| 172 | + """Convert the weights of a model from SpConv to TorchSparse. |
| 173 | +
|
| 174 | + :param ckpt_before: Path to the SpConv checkpoint |
| 175 | + :type ckpt_before: str |
| 176 | + :param ckpt_after: Path to the output folder of the converted checkpoint. |
| 177 | + :type ckpt_after: str |
| 178 | + :param v_spconv: SpConv version used for the weights. Can be one of 1 or 2, defaults to "1" |
| 179 | + :type v_spconv: str, optional |
| 180 | + :param framework: From which framework does the model weight comes from, choose one of mmdet3d or openpc, defaults to "mmdet3d" |
| 181 | + :type framework: str, optional |
| 182 | + """ |
| 183 | + # ckpt_before, ckpt_after, v_spconv="1", framework="mmdet3d" |
| 184 | + |
| 185 | + # argument parser |
| 186 | + parser = argparse.ArgumentParser(description="Convert SpConv model to TorchSparse model") |
| 187 | + parser.add_argument("--ckpt_before", help="Path to the SpConv checkpoint") |
| 188 | + parser.add_argument("--ckpt_after", help="Path to the output folder of the converted checkpoint.") |
| 189 | + parser.add_argument("--cfg_path", help="Path to the config file of the model") |
| 190 | + parser.add_argument("--v_spconv", default="1", help="SpConv version used for the weights. Can be one of 1 or 2") |
| 191 | + parser.add_argument("--framework", default="mmdet3d", help="From which framework does the model weight comes from, choose one of mmdet3d or openpc") |
| 192 | + args = parser.parse_args() |
| 193 | + |
| 194 | + # Check the plugin argument |
| 195 | + assert args.framework in ['mmdet3d', 'openpc'], "plugin argument can only be mmdet3d or openpcdet" |
| 196 | + assert args.v_spconv in ['1', '2'], "v_spconv argument can only be 1 or 2" |
| 197 | + |
| 198 | + legacy = True if args.v_spconv == "1" else False |
| 199 | + cfg_path = args.cfg_path |
| 200 | + |
| 201 | + model = build_mmdet_model_from_cfg(cfg_path, args.ckpt_before) if args.framework == "mmdet3d" else build_opc_model_from_cfg(cfg_path) |
| 202 | + convert_model_weights( |
| 203 | + ckpt_before=args.ckpt_before, |
| 204 | + ckpt_after=args.ckpt_after, |
| 205 | + model=model, |
| 206 | + legacy=legacy) |
| 207 | + |
| 208 | + |
| 209 | +def convert_weights(ckpt_before: str, ckpt_after: str, cfg_path: str, v_spconv: int = 1, framework: str = "mmdet3d"): |
| 210 | + """Convert the weights of a model from SpConv to TorchSparse. |
| 211 | +
|
| 212 | + :param ckpt_before: _description_ |
| 213 | + :type ckpt_before: str |
| 214 | + :param ckpt_after: _description_ |
| 215 | + :type ckpt_after: str |
| 216 | + :param cfg_path: _description_ |
| 217 | + :type cfg_path: str |
| 218 | + :param v_spconv: _description_, defaults to 1 |
| 219 | + :type v_spconv: int, optional |
| 220 | + :param framework: _description_, defaults to "mmdet3d" |
| 221 | + :type framework: str, optional |
| 222 | + """ |
| 223 | + |
| 224 | + # Check the plugin argument |
| 225 | + assert framework in ['mmdet3d', 'openpc'], "plugin argument can only be mmdet3d or openpcdet" |
| 226 | + assert v_spconv in [1, 2], "v_spconv argument can only be 1 or 2" |
| 227 | + |
| 228 | + legacy = True if v_spconv == 1 else False |
| 229 | + |
| 230 | + model = build_mmdet_model_from_cfg(cfg_path, ckpt_before) if framework == "mmdet3d" else build_opc_model_from_cfg(cfg_path) |
| 231 | + convert_model_weights( |
| 232 | + ckpt_before=ckpt_before, |
| 233 | + ckpt_after=ckpt_after, |
| 234 | + model=model, |
| 235 | + legacy=legacy) |
| 236 | + |
| 237 | + |
| 238 | +if __name__ == "__main__": |
| 239 | + convert_weights_cmd() |
| 240 | + print("Conversion completed") |
0 commit comments