From 363d7145a6ec3e84e63472cc54e9fa705dbb41e2 Mon Sep 17 00:00:00 2001 From: Piotr Duda Date: Tue, 20 Oct 2026 17:09:21 +0200 Subject: [PATCH 1/3] Track each transformers pipeline call once pipeline() loads the model before Pipeline.__init__ runs, so the model was registered with forward hooks of its own, and every pipeline call produced two inference events: one from the pipeline patch and one from the model inside it. The pipeline patch now marks the call on a thread-local counter and the model's forward hook skips while it is set. Direct model calls are still tracked. Closes #70 --- CHANGELOG.md | 6 + tests/compat/test_transformers_compat.py | 6 - tests/test_integrations_transformers.py | 164 +++++++++++++++++++++++ wildedge/integrations/transformers.py | 17 ++- 4 files changed, 185 insertions(+), 8 deletions(-) create mode 100644 tests/test_integrations_transformers.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 99dc1f5..fae6204 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,12 @@ 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 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. The model's hooks + now skip calls made inside a tracked pipeline call; calling the model + directly is still tracked. ## 0.2.2 - 2026-09-30 diff --git a/tests/compat/test_transformers_compat.py b/tests/compat/test_transformers_compat.py index 9d4e8ae..0ddb803 100644 --- a/tests/compat/test_transformers_compat.py +++ b/tests/compat/test_transformers_compat.py @@ -1,6 +1,5 @@ from __future__ import annotations -import pytest import torch import transformers @@ -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"] diff --git a/tests/test_integrations_transformers.py b/tests/test_integrations_transformers.py new file mode 100644 index 0000000..6bdf3db --- /dev/null +++ b/tests/test_integrations_transformers.py @@ -0,0 +1,164 @@ +"""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): + self.model = model + self.fail = fail + + def __call__(self, inputs, *args, **kwargs): + if self.fail: + raise RuntimeError("tokenizer exploded") + self.model(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) -> ModelHandle: + info = ModelInfo( + model_name="tiny-bert", + model_version="1", + model_source="local", + model_format="transformers", + ) + return ModelHandle(model_id="tiny-bert", 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 test_suppression_is_per_thread(patched_pipeline): + events: list = [] + _, model = tracked_pipeline(patched_pipeline, events) + + # This thread is inside a tracked pipeline call; another thread is not. + tf_mod._tl.pipeline_call_depth = 1 + try: + model(FakeTensor()) # suppressed: the pipeline call records it + other = threading.Thread(target=lambda: model(FakeTensor())) + other.start() + other.join() + finally: + tf_mod._tl.pipeline_call_depth = 0 + + assert len(inference_events(events)) == 1 # only the other thread's call diff --git a/wildedge/integrations/transformers.py b/wildedge/integrations/transformers.py index e5a3b2c..5e0dc20 100644 --- a/wildedge/integrations/transformers.py +++ b/wildedge/integrations/transformers.py @@ -41,11 +41,18 @@ # 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. +# Thread-local state: +# - inside_pipeline_init: suppress from_pretrained tracking when called inside +# Pipeline.__init__ so the pipeline-level tracking takes precedence. +# - pipeline_call_depth: > 0 while a tracked pipeline call runs, so the forward +# hooks of the model inside it don't record the same inference again. _tl = threading.local() +def inside_tracked_pipeline_call() -> bool: + return getattr(_tl, "pipeline_call_depth", 0) > 0 + + debug_transformers_failure = functools.partial(debug_failure, "transformers") @@ -308,6 +315,9 @@ def pre_hook(module, args): # type: ignore[no-untyped-def] _local.t0 = time.perf_counter() def post_hook(module, args, output): # type: ignore[no-untyped-def] + # A pipeline call around this forward pass records the event. + if inside_tracked_pipeline_call(): + return t0 = getattr(_local, "t0", None) duration_ms = elapsed_ms(t0) if t0 is not None else 0 @@ -419,6 +429,7 @@ def patched_call(self, inputs, *args, **kwargs): # type: ignore[no-untyped-def] input_modality, output_modality = pipeline_modalities(task) t0 = time.perf_counter() + _tl.pipeline_call_depth = getattr(_tl, "pipeline_call_depth", 0) + 1 try: outputs = original_call(self, inputs, *args, **kwargs) duration_ms = elapsed_ms(t0) @@ -439,6 +450,8 @@ 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_call_depth -= 1 patched_call.__wildedge_patch_name__ = PIPELINE_CALL_PATCH_NAME # type: ignore[attr-defined] patched_call.__wildedge_original_call__ = original_call # type: ignore[attr-defined] From 622900474c17d88379311e26b0d13b7cfb90a186 Mon Sep 17 00:00:00 2001 From: Piotr Duda Date: Tue, 20 Oct 2026 17:18:02 +0200 Subject: [PATCH 2/3] Keep pipeline tracking state in a typed thread-local The two per-thread flags were attributes on a bare threading.local read with getattr defaults. A threading.local subclass now declares both, the forward pre-hook skips inside a tracked pipeline call like the post-hook does, and the cross-thread test checks behaviour instead of setting the counter by hand. --- tests/test_integrations_transformers.py | 39 ++++++++++++++++++------- wildedge/integrations/transformers.py | 33 +++++++++++++-------- 2 files changed, 49 insertions(+), 23 deletions(-) diff --git a/tests/test_integrations_transformers.py b/tests/test_integrations_transformers.py index 6bdf3db..3b26520 100644 --- a/tests/test_integrations_transformers.py +++ b/tests/test_integrations_transformers.py @@ -147,18 +147,35 @@ def test_untracked_pipeline_does_not_suppress_model_hooks(patched_pipeline): assert len(inference_events(events)) == 1 -def test_suppression_is_per_thread(patched_pipeline): - events: list = [] - _, model = tracked_pipeline(patched_pipeline, events) +class CallsFromAnotherThreadToo: + """Pipeline model that also runs the hooked model on a second thread.""" + + def __init__(self, model: FakeModel) -> None: + self.model = model - # This thread is inside a tracked pipeline call; another thread is not. - tf_mod._tl.pipeline_call_depth = 1 - try: - model(FakeTensor()) # suppressed: the pipeline call records it - other = threading.Thread(target=lambda: model(FakeTensor())) + def __call__(self, input_ids): + other = threading.Thread(target=self.model, args=(input_ids,)) other.start() other.join() - finally: - tf_mod._tl.pipeline_call_depth = 0 + return self.model(input_ids) + + +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(CallsFromAnotherThreadToo(model)) + extractor.install_hooks(pipe, handle) + + pipe("hello") - assert len(inference_events(events)) == 1 # only the other thread's call + # 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 diff --git a/wildedge/integrations/transformers.py b/wildedge/integrations/transformers.py index 5e0dc20..bf33700 100644 --- a/wildedge/integrations/transformers.py +++ b/wildedge/integrations/transformers.py @@ -41,16 +41,22 @@ # Per-instance attribute that stores the ModelHandle on a pipeline object. PIPELINE_HANDLE_ATTR = "__wildedge_pipeline_handle__" -# Thread-local state: -# - inside_pipeline_init: suppress from_pretrained tracking when called inside -# Pipeline.__init__ so the pipeline-level tracking takes precedence. -# - pipeline_call_depth: > 0 while a tracked pipeline call runs, so the forward -# hooks of the model inside it don't record the same inference again. -_tl = threading.local() +class _ThreadState(threading.local): + """Per-thread flags that keep pipeline-level tracking the only record. -def inside_tracked_pipeline_call() -> bool: - return getattr(_tl, "pipeline_call_depth", 0) > 0 + inside_pipeline_init: from_pretrained calls made by Pipeline.__init__ are + not tracked on their own. + pipeline_call_depth: while above zero, a tracked pipeline call is running + and the forward hooks of the model inside it record nothing. + """ + + def __init__(self) -> None: + self.inside_pipeline_init = False + self.pipeline_call_depth = 0 + + +_tl = _ThreadState() debug_transformers_failure = functools.partial(debug_failure, "transformers") @@ -311,12 +317,15 @@ def install_hooks(self, obj: object, handle: ModelHandle) -> None: _, _, arch = extract_model_config(obj) task_hint = infer_task_from_arch(arch) + # Forward passes inside a tracked pipeline call are recorded by + # the pipeline, so both hooks skip them. def pre_hook(module, args): # type: ignore[no-untyped-def] + if _tl.pipeline_call_depth: + return _local.t0 = time.perf_counter() def post_hook(module, args, output): # type: ignore[no-untyped-def] - # A pipeline call around this forward pass records the event. - if inside_tracked_pipeline_call(): + if _tl.pipeline_call_depth: return t0 = getattr(_local, "t0", None) duration_ms = elapsed_ms(t0) if t0 is not None else 0 @@ -429,7 +438,7 @@ def patched_call(self, inputs, *args, **kwargs): # type: ignore[no-untyped-def] input_modality, output_modality = pipeline_modalities(task) t0 = time.perf_counter() - _tl.pipeline_call_depth = getattr(_tl, "pipeline_call_depth", 0) + 1 + _tl.pipeline_call_depth += 1 try: outputs = original_call(self, inputs, *args, **kwargs) duration_ms = elapsed_ms(t0) @@ -470,7 +479,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 = ( From 2fd5324da6fd10b2ff6b6d6e6199318e678a022f Mon Sep 17 00:00:00 2001 From: Piotr Duda Date: Tue, 20 Oct 2026 17:27:03 +0200 Subject: [PATCH 3/3] Only suppress the pipeline's own model during a pipeline call Review of #77: the hook guard checked whether any tracked pipeline call was running on the thread, so a custom pipeline that also ran a second tracked model silently dropped that model's events. Each thread now counts the models wrapped by running tracked pipeline calls (by id, for nesting), and a forward hook skips only when its own model is among them. The changelog no longer claims one event per call for generator and dataset inputs, which run lazily after __call__ returns; that is #78. --- CHANGELOG.md | 14 ++--- tests/test_integrations_transformers.py | 69 ++++++++++++++++++++----- wildedge/integrations/transformers.py | 25 +++++---- 3 files changed, 78 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fae6204..8e7d2c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,12 +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 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. The model's hooks - now skip calls made inside a tracked pipeline call; calling the model - directly is still tracked. +- 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 diff --git a/tests/test_integrations_transformers.py b/tests/test_integrations_transformers.py index 3b26520..c11193b 100644 --- a/tests/test_integrations_transformers.py +++ b/tests/test_integrations_transformers.py @@ -49,14 +49,18 @@ def make_pipeline_class(): class Pipeline: task = "text-classification" - def __init__(self, model, fail=False): + 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. @@ -73,14 +77,14 @@ def patched_pipeline(monkeypatch): return pipeline_cls -def make_handle(events: list) -> ModelHandle: +def make_handle(events: list, model_id: str = "tiny-bert") -> ModelHandle: info = ModelInfo( - model_name="tiny-bert", + model_name=model_id, model_version="1", model_source="local", model_format="transformers", ) - return ModelHandle(model_id="tiny-bert", info=info, publish=events.append) + return ModelHandle(model_id=model_id, info=info, publish=events.append) def tracked_pipeline(pipeline_cls, events, fail=False): @@ -147,17 +151,13 @@ def test_untracked_pipeline_does_not_suppress_model_hooks(patched_pipeline): assert len(inference_events(events)) == 1 -class CallsFromAnotherThreadToo: - """Pipeline model that also runs the hooked model on a second thread.""" - - def __init__(self, model: FakeModel) -> None: - self.model = model - - def __call__(self, input_ids): - other = threading.Thread(target=self.model, args=(input_ids,)) +def call_on_another_thread(model: FakeModel): + def run(input_ids): + other = threading.Thread(target=model, args=(input_ids,)) other.start() other.join() - return self.model(input_ids) + + return run def test_model_call_on_another_thread_during_pipeline_call_is_tracked( @@ -168,7 +168,7 @@ def test_model_call_on_another_thread_during_pipeline_call_is_tracked( handle = make_handle(events) model = FakeModel() extractor.install_hooks(model, handle) - pipe = patched_pipeline(CallsFromAnotherThreadToo(model)) + pipe = patched_pipeline(model, extra_models=[call_on_another_thread(model)]) extractor.install_hooks(pipe, handle) pipe("hello") @@ -179,3 +179,44 @@ def test_model_call_on_another_thread_during_pipeline_call_is_tracked( 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) diff --git a/wildedge/integrations/transformers.py b/wildedge/integrations/transformers.py index bf33700..5c50956 100644 --- a/wildedge/integrations/transformers.py +++ b/wildedge/integrations/transformers.py @@ -6,6 +6,7 @@ import os import threading import time +from collections import Counter from typing import TYPE_CHECKING from wildedge import constants @@ -43,17 +44,18 @@ class _ThreadState(threading.local): - """Per-thread flags that keep pipeline-level tracking the only record. + """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_call_depth: while above zero, a tracked pipeline call is running - and the forward hooks of the model inside it record nothing. + 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_call_depth = 0 + self.pipeline_models: Counter[int] = Counter() _tl = _ThreadState() @@ -317,15 +319,15 @@ def install_hooks(self, obj: object, handle: ModelHandle) -> None: _, _, arch = extract_model_config(obj) task_hint = infer_task_from_arch(arch) - # Forward passes inside a tracked pipeline call are recorded by - # the pipeline, so both hooks skip them. + # 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_call_depth: + 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_call_depth: + if _tl.pipeline_models[id(module)]: return t0 = getattr(_local, "t0", None) duration_ms = elapsed_ms(t0) if t0 is not None else 0 @@ -438,7 +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() - _tl.pipeline_call_depth += 1 + 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) @@ -460,7 +463,9 @@ def patched_call(self, inputs, *args, **kwargs): # type: ignore[no-untyped-def] ) raise finally: - _tl.pipeline_call_depth -= 1 + _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]