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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ under Unreleased and move into a version section at release time.
session created without an `id` falls back to the file name too, and
`model_version` 0, negative or INT64_MAX (the exporters' "unset") is sent as
`unknown` instead of `9223372036854775807`.
- transformers pipelines called with a string or a list record one inference
event per call instead of two. `pipeline()` loads the model before
`Pipeline.__init__` runs, so the model was registered with its own forward
hooks, and each pipeline call was tracked by the pipeline and again by the
model inside it. That model's hooks now skip forward passes inside a
tracked call of its pipeline; other models the pipeline runs, and direct
calls to the model, are still tracked. Generator and dataset inputs, which
run lazily, are not covered yet (#78).

## 0.2.2 - 2026-09-30

Expand Down
6 changes: 0 additions & 6 deletions tests/compat/test_transformers_compat.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import pytest
import torch
import transformers

Expand Down Expand Up @@ -34,11 +33,6 @@ def test_from_pretrained_load_and_forward_are_tracked(compat_client, tmp_path):
assert inference["inference"]["success"] is True


@pytest.mark.xfail(
strict=True,
reason="pipeline() calls are counted twice: the inner model keeps its "
"forward hooks after the pipeline supersedes it (#70)",
)
def test_pipeline_load_and_call_are_tracked(compat_client, tmp_path):
_save_tiny_bert(tmp_path)
vocab = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", "hello", "world"]
Expand Down
222 changes: 222 additions & 0 deletions tests/test_integrations_transformers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
"""Inference tracking for transformers pipelines and models (#70)."""

from __future__ import annotations

import threading
import types

import pytest

import wildedge.integrations.transformers as tf_mod
from wildedge.integrations.transformers import TransformersExtractor
from wildedge.model import ModelHandle, ModelInfo


class FakeModel:
"""Enough of a torch module for install_hooks: forward hooks and a config."""

config = types.SimpleNamespace(
name_or_path="tiny-bert",
model_type="bert",
architectures=["BertForSequenceClassification"],
)

def __init__(self) -> None:
self.pre_hooks: list = []
self.post_hooks: list = []

def register_forward_pre_hook(self, hook):
self.pre_hooks.append(hook)

def register_forward_hook(self, hook):
self.post_hooks.append(hook)

def __call__(self, input_ids):
args = (input_ids,)
for hook in self.pre_hooks:
hook(self, args)
output = [[0.1, 0.9]]
for hook in self.post_hooks:
hook(self, args, output)
return output


class FakeTensor:
shape = (1, 4)


def make_pipeline_class():
class Pipeline:
task = "text-classification"

def __init__(self, model, fail=False, extra_models=()):
self.model = model
self.fail = fail
# Other models a custom pipeline runs, e.g. from _forward.
self.extra_models = list(extra_models)

def __call__(self, inputs, *args, **kwargs):
if self.fail:
raise RuntimeError("tokenizer exploded")
self.model(FakeTensor())
for extra in self.extra_models:
extra(FakeTensor())
return [{"label": "LABEL_1", "score": 0.9}]

# is_pipeline() looks for a class named Pipeline from a transformers module.
Pipeline.__module__ = "transformers.pipelines.base"
return Pipeline


@pytest.fixture
def patched_pipeline(monkeypatch):
pipeline_cls = make_pipeline_class()
fake_transformers = types.SimpleNamespace(Pipeline=pipeline_cls)
monkeypatch.setattr(tf_mod, "_transformers", fake_transformers)
TransformersExtractor._patch_pipeline_call()
return pipeline_cls


def make_handle(events: list, model_id: str = "tiny-bert") -> ModelHandle:
info = ModelInfo(
model_name=model_id,
model_version="1",
model_source="local",
model_format="transformers",
)
return ModelHandle(model_id=model_id, info=info, publish=events.append)


def tracked_pipeline(pipeline_cls, events, fail=False):
"""A pipeline wrapping a model, both with hooks, as after pipeline() loads."""
extractor = TransformersExtractor()
handle = make_handle(events)
model = FakeModel()
extractor.install_hooks(model, handle) # from_pretrained ran first
pipe = pipeline_cls(model, fail=fail)
extractor.install_hooks(pipe, handle) # then the pipeline superseded it
return pipe, model


def inference_events(events: list) -> list:
return [e for e in events if e["event_type"] == "inference"]


def test_pipeline_call_is_tracked_once(patched_pipeline):
events: list = []
pipe, _ = tracked_pipeline(patched_pipeline, events)

pipe("hello world")

inferences = inference_events(events)
assert len(inferences) == 1
inference = inferences[0]["inference"]
# The pipeline-level event, with what only the pipeline knows.
assert inference["batch_size"] == 1
assert inference["input_meta"]["word_count"] == 2
assert inference["output_meta"]["task"] == "classification"


def test_direct_model_call_is_still_tracked(patched_pipeline):
events: list = []
_, model = tracked_pipeline(patched_pipeline, events)

model(FakeTensor())

inferences = inference_events(events)
assert len(inferences) == 1
assert inferences[0]["inference"]["input_meta"]["token_count"] == 4


def test_failed_pipeline_call_resets_suppression(patched_pipeline):
events: list = []
pipe, model = tracked_pipeline(patched_pipeline, events, fail=True)

with pytest.raises(RuntimeError, match="tokenizer exploded"):
pipe("hello")
assert [e["event_type"] for e in events] == ["error"]

model(FakeTensor())
assert len(inference_events(events)) == 1


def test_untracked_pipeline_does_not_suppress_model_hooks(patched_pipeline):
events: list = []
model = FakeModel()
TransformersExtractor().install_hooks(model, make_handle(events))
pipe = patched_pipeline(model) # no handle on the pipeline itself

pipe("hello")

assert len(inference_events(events)) == 1


def call_on_another_thread(model: FakeModel):
def run(input_ids):
other = threading.Thread(target=model, args=(input_ids,))
other.start()
other.join()

return run


def test_model_call_on_another_thread_during_pipeline_call_is_tracked(
patched_pipeline,
):
events: list = []
extractor = TransformersExtractor()
handle = make_handle(events)
model = FakeModel()
extractor.install_hooks(model, handle)
pipe = patched_pipeline(model, extra_models=[call_on_another_thread(model)])
extractor.install_hooks(pipe, handle)

pipe("hello")

# The pipeline's own event, and the other thread's model call; the model
# call on the pipeline's thread is part of the pipeline event.
metas = [e["inference"]["input_meta"] for e in inference_events(events)]
assert len(metas) == 2
assert {"char_count": 5, "word_count": 1} in metas # the pipeline call
assert {"token_count": 4} in metas # the other thread's model call


def test_other_model_called_during_pipeline_call_is_tracked(patched_pipeline):
"""A custom pipeline that also runs a second tracked model keeps both."""
events: list = []
extractor = TransformersExtractor()
main_model, reranker = FakeModel(), FakeModel()
main_handle = make_handle(events)
reranker_handle = make_handle(events, model_id="reranker")
extractor.install_hooks(main_model, main_handle)
extractor.install_hooks(reranker, reranker_handle)
pipe = patched_pipeline(main_model, extra_models=[reranker])
extractor.install_hooks(pipe, main_handle)

pipe("hello")

ids = sorted(e["model_id"] for e in inference_events(events))
assert ids == ["reranker", "tiny-bert"]


def test_nested_pipeline_calls_keep_suppressing_until_the_outer_ends(
patched_pipeline,
):
events: list = []
extractor = TransformersExtractor()
handle = make_handle(events)
model = FakeModel()
extractor.install_hooks(model, handle)
inner = patched_pipeline(model)
extractor.install_hooks(inner, handle)
# The outer pipeline wraps the same model and calls the inner one, then
# runs the model again after the inner call has returned.
outer = patched_pipeline(model, extra_models=[lambda _: inner("x"), model])
extractor.install_hooks(outer, handle)

outer("hello")

# One event per pipeline call; no model events from inside either.
inferences = inference_events(events)
assert len(inferences) == 2
assert all("word_count" in e["inference"]["input_meta"] for e in inferences)
35 changes: 31 additions & 4 deletions wildedge/integrations/transformers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import os
import threading
import time
from collections import Counter
from typing import TYPE_CHECKING

from wildedge import constants
Expand Down Expand Up @@ -41,9 +42,23 @@
# Per-instance attribute that stores the ModelHandle on a pipeline object.
PIPELINE_HANDLE_ATTR = "__wildedge_pipeline_handle__"

# Thread-local flag: suppress from_pretrained tracking when called inside
# Pipeline.__init__ so the pipeline-level tracking takes precedence.
_tl = threading.local()

class _ThreadState(threading.local):
"""Per-thread state that keeps pipeline-level tracking the only record.

inside_pipeline_init: from_pretrained calls made by Pipeline.__init__ are
not tracked on their own.
pipeline_models: id() of the model each running tracked pipeline call
wraps, counted for nesting. That model's forward hooks record nothing
while it is here; other models called during the pipeline call do.
"""

def __init__(self) -> None:
self.inside_pipeline_init = False
self.pipeline_models: Counter[int] = Counter()


_tl = _ThreadState()


debug_transformers_failure = functools.partial(debug_failure, "transformers")
Expand Down Expand Up @@ -304,10 +319,16 @@ def install_hooks(self, obj: object, handle: ModelHandle) -> None:
_, _, arch = extract_model_config(obj)
task_hint = infer_task_from_arch(arch)

# A tracked pipeline call records its own model's forward passes,
# so both hooks skip them.
def pre_hook(module, args): # type: ignore[no-untyped-def]
if _tl.pipeline_models[id(module)]:
return
_local.t0 = time.perf_counter()

def post_hook(module, args, output): # type: ignore[no-untyped-def]
if _tl.pipeline_models[id(module)]:
return
t0 = getattr(_local, "t0", None)
duration_ms = elapsed_ms(t0) if t0 is not None else 0

Expand Down Expand Up @@ -419,6 +440,8 @@ def patched_call(self, inputs, *args, **kwargs): # type: ignore[no-untyped-def]
input_modality, output_modality = pipeline_modalities(task)

t0 = time.perf_counter()
model_key = id(getattr(self, "model", None))
_tl.pipeline_models[model_key] += 1
try:
outputs = original_call(self, inputs, *args, **kwargs)
duration_ms = elapsed_ms(t0)
Expand All @@ -439,6 +462,10 @@ def patched_call(self, inputs, *args, **kwargs): # type: ignore[no-untyped-def]
error_message=str(exc)[: constants.ERROR_MSG_MAX_LEN],
)
raise
finally:
_tl.pipeline_models[model_key] -= 1
if not _tl.pipeline_models[model_key]:
del _tl.pipeline_models[model_key]

patched_call.__wildedge_patch_name__ = PIPELINE_CALL_PATCH_NAME # type: ignore[attr-defined]
patched_call.__wildedge_original_call__ = original_call # type: ignore[attr-defined]
Expand All @@ -457,7 +484,7 @@ def _patch_from_pretrained(cls, client_ref: object) -> None:

def patched_from_pretrained(model_cls, *args, **kwargs): # type: ignore[no-untyped-def]
# Don't double-track models loaded inside Pipeline.__init__
if getattr(_tl, "inside_pipeline_init", False):
if _tl.inside_pipeline_init:
return original_func(model_cls, *args, **kwargs)
c = client_ref() # type: ignore[call-arg]
hub_before = (
Expand Down
Loading