Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix loading of quantized YOLOv8 model #1498

Merged
merged 4 commits into from
Mar 30, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 13 additions & 10 deletions src/sparseml/yolov8/trainers.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,22 +205,13 @@ def setup_model(self):
LOGGER.info("Loaded previous weights from sparseml checkpoint")
return ckpt

def _modify_arch_for_quantization(self):
layer_map = {"Bottleneck": Bottleneck, "Conv": Conv}
for name, layer in self.model.named_modules():
cls_name = layer.__class__.__name__
if cls_name in layer_map:
submodule_path = name.split(".")
parent_module = _get_submodule(self.model, submodule_path[:-1])
setattr(parent_module, submodule_path[-1], layer_map[cls_name](layer))

def _build_managers(self, ckpt: Optional[dict]):
if self.args.recipe is not None:
self.manager = ScheduledModifierManager.from_yaml(
self.args.recipe, recipe_variables=self.args.recipe_args
)
if self.manager.quantization_modifiers:
self._modify_arch_for_quantization()
_modify_arch_for_quantization(self.model)

if ckpt is None:
return
Expand Down Expand Up @@ -557,6 +548,8 @@ def _load(self, weights: str):
"Applying structure from sparseml checkpoint "
f"at epoch {self.ckpt['epoch']}"
)
if manager.quantization_modifiers:
_modify_arch_for_quantization(self.model)
manager.apply_structure(self.model, epoch=epoch)
else:
LOGGER.info("No recipe from in sparseml checkpoint")
Expand Down Expand Up @@ -775,3 +768,13 @@ def _get_submodule(module: torch.nn.Module, path: List[str]) -> torch.nn.Module:
if not path:
return module
return _get_submodule(getattr(module, path[0]), path[1:])


def _modify_arch_for_quantization(model):
layer_map = {"Bottleneck": Bottleneck, "Conv": Conv}
for name, layer in model.named_modules():
cls_name = layer.__class__.__name__
if cls_name in layer_map:
submodule_path = name.split(".")
parent_module = _get_submodule(model, submodule_path[:-1])
setattr(parent_module, submodule_path[-1], layer_map[cls_name](layer))