Skip to content
Merged
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ under Unreleased and move into a version section at release time.

### Fixed

- timm models now use the requested architecture/variant name for model identity
instead of the Python class name, so models such as resnet18 and resnet50 no
longer share telemetry. Manual registration falls back to timm architecture
metadata, and explicit model IDs retain priority.

- Ultralytics `model.predict()` now records inference telemetry. Instrumentation
patches `predict`, which `model(...)` delegates to, so both entry points are
tracked exactly once.
Expand Down
33 changes: 25 additions & 8 deletions tests/compat/test_timm_compat.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import pytest
import timm
import torch

Expand All @@ -18,14 +17,32 @@ def test_timm_create_model_and_forward_are_tracked(compat_client):
assert inference["inference"]["input_modality"] == "image"


@pytest.mark.xfail(
strict=True,
reason="timm models are registered by class name, so architectures collide (#73)",
)
def test_timm_architectures_get_their_own_ids(compat_client):
compat_client.instrument("timm")
# Neither is loaded by another test, so each should add one model_load.
timm.create_model("resnet34", pretrained=False)
timm.create_model("resnet50", pretrained=False)
models = [
timm.create_model(name, pretrained=False).eval()
for name in ("resnet34", "resnet50")
]
with torch.no_grad():
for model in models:
model(torch.randn(1, 3, 64, 64))
ids = {e["model_id"] for e in compat_client.of_type("model_load")}
assert len(ids) == 2
assert ids == {"resnet34", "resnet50"}
assert {e["model_id"] for e in compat_client.of_type("inference")} == ids
assert {compat_client.registry.models[name].model_name for name in ids} == ids


def test_repeated_architecture_reuses_identity(compat_client):
compat_client.instrument("timm")
models = [
timm.create_model(model_name="resnet18", pretrained=False).eval()
for _ in range(2)
]
with torch.no_grad():
for model in models:
model(torch.randn(1, 3, 64, 64))
events = compat_client.of_type("inference")
assert len(events) == 2
assert {event["model_id"] for event in events} == {"resnet18"}
assert compat_client.registry.models["resnet18"].model_name == "resnet18"
52 changes: 52 additions & 0 deletions tests/test_integrations_pytorch.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@

from __future__ import annotations

from types import SimpleNamespace
from unittest.mock import MagicMock

import pytest

import wildedge.integrations.pytorch as pytorch_mod
from wildedge.integrations.pytorch import (
PytorchExtractor,
)
Expand Down Expand Up @@ -163,3 +167,51 @@ def test_install_hooks_sets_detected_accelerator(self, publish_spy):
handle = make_handle(publish_spy)
self.extractor.install_hooks(model, handle)
assert handle.detected_accelerator == "cpu"


def test_timm_config_identity_and_explicit_override():
model = _FakeTorchModel()
model.pretrained_cfg = {"architecture": "resnet50"}
extractor = PytorchExtractor()
model_id, info = extractor.extract_info(model, {})
assert model_id == info.model_name == "resnet50"
model_id, info = extractor.extract_info(model, {"id": "custom-model"})
assert model_id == "custom-model"
assert info.model_name == "resnet50"


def test_timm_requested_variant_takes_priority_over_config():
model = _FakeTorchModel()
model.pretrained_cfg = {"architecture": "resnet50"}
model.__wildedge_timm_model_name__ = "resnet50.a1_in1k"
model_id, info = PytorchExtractor().extract_info(model, {})
assert model_id == info.model_name == "resnet50.a1_in1k"


def test_timm_invalid_config_falls_back_to_class():
model = _FakeTorchModel()
model.pretrained_cfg = {"architecture": None}
model.default_cfg = {"architecture": 123}
model_id, info = PytorchExtractor().extract_info(model, {})
assert model_id == info.model_name == "_FakeTorchModel"


@pytest.mark.parametrize("keyword", [False, True])
@pytest.mark.parametrize("name", ["resnet50.a1_in1k", "hf-hub:example/resnet50"])
def test_timm_patch_retains_requested_name(monkeypatch, keyword, name):
model = _FakeTorchModel()
fake_timm = SimpleNamespace(create_model=MagicMock(return_value=model))
monkeypatch.setattr(pytorch_mod, "_timm", fake_timm)
monkeypatch.setattr(pytorch_mod, "_timm_patched", False)
client = MagicMock(closed=False)
client._diff_hub_caches.return_value = []
PytorchExtractor.install_timm_patch(lambda: client)
result = (
fake_timm.create_model(model_name=name)
if keyword
else fake_timm.create_model(name)
)
assert result is model
model_id, info = PytorchExtractor().extract_info(result, {})
assert model_id == info.model_name == name
client._on_model_auto_loaded.assert_called_once()
32 changes: 28 additions & 4 deletions wildedge/integrations/pytorch.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
_timm_patched = False
_TIMM_PATCH_LOCK = threading.Lock()
TIMM_AUTO_LOAD_PATCH_NAME = "timm_auto_load"
TIMM_MODEL_NAME_ATTR = "__wildedge_timm_model_name__"


debug_pytorch_failure = functools.partial(debug_failure, "pytorch")
Expand Down Expand Up @@ -164,6 +165,20 @@ def classification_output_meta(
)


def timm_model_name(obj: object) -> str | None:
"""Prefer the full requested name, including pretrained tags or hub paths."""
name = getattr(obj, TIMM_MODEL_NAME_ATTR, None)
if isinstance(name, str) and name:
return name
for key in ("pretrained_cfg", "default_cfg"):
config = getattr(obj, key, None)
if isinstance(config, dict):
name = config.get("architecture")
if isinstance(name, str) and name:
return name
return None


class PytorchExtractor(BaseExtractor):
def can_handle(self, obj: object) -> bool:
return is_torch_module(obj)
Expand All @@ -172,9 +187,15 @@ def extract_info(
self, obj: object, overrides: dict
) -> tuple[str | None, ModelInfo]:
class_name = type(obj).__name__
model_id = overrides.pop("id", None) or class_name

if class_name in _GENERIC_MODULE_NAMES:
model_name = timm_model_name(obj) or class_name
explicit_id = overrides.pop("id", None)
model_id = explicit_id or model_name

if (
model_name == class_name
and class_name in _GENERIC_MODULE_NAMES
and not explicit_id
):
logger.warning(
"wildedge: PyTorch model_id defaults to generic class name '%s' - "
"pass model_id= to register_model() for a stable unique ID",
Expand All @@ -187,7 +208,7 @@ def extract_info(
source = overrides.pop("source", "local")

info = ModelInfo(
model_name=class_name,
model_name=model_name,
model_version=version,
model_source=source,
model_format="pytorch",
Expand Down Expand Up @@ -315,6 +336,9 @@ def patched_create_model(*args, **kwargs): # type: ignore[no-untyped-def]
load_ms = elapsed_ms(t0)
logger.debug("wildedge: timm.create_model done load_ms=%d", load_ms)
if c is not None and not c.closed:
name = args[0] if args else kwargs.get("model_name")
if isinstance(name, str) and name:
setattr(model, TIMM_MODEL_NAME_ATTR, name)
downloads = c._diff_hub_caches(hub_before, load_ms) or None
c._on_model_auto_loaded(model, load_ms=load_ms, downloads=downloads)
return model
Expand Down
Loading