|
| 1 | +from typing import Any, Callable, Dict, Mapping, Optional, Tuple |
| 2 | + |
| 3 | +from copy import copy, deepcopy |
| 4 | + |
| 5 | +from wrapt import BoundFunctionWrapper, FunctionWrapper, wrap_object |
| 6 | + |
| 7 | +from parea import trace |
| 8 | + |
| 9 | +_DSPY_MODULE_NAME = "dspy" |
| 10 | +_DSP_MODULE_NAME = "dsp" |
| 11 | + |
| 12 | + |
| 13 | +class DSPyInstrumentor: |
| 14 | + |
| 15 | + def instrument(self) -> None: |
| 16 | + # Instrument LM (language model) calls |
| 17 | + from dsp.modules.lm import LM |
| 18 | + from dspy import Predict |
| 19 | + |
| 20 | + language_model_classes = LM.__subclasses__() |
| 21 | + for lm in language_model_classes: |
| 22 | + wrap_object( |
| 23 | + module=_DSP_MODULE_NAME, |
| 24 | + name=lm.__name__ + ".basic_request", |
| 25 | + factory=CopyableFunctionWrapper, |
| 26 | + args=(_GeneralDSPyWrapper("request"),), |
| 27 | + ) |
| 28 | + |
| 29 | + # Predict is a concrete (non-abstract) class that may be invoked |
| 30 | + # directly, but DSPy also has subclasses of Predict that override the |
| 31 | + # forward method. We instrument both the forward methods of the base |
| 32 | + # class and all subclasses. |
| 33 | + wrap_object( |
| 34 | + module=_DSPY_MODULE_NAME, |
| 35 | + name="Predict.forward", |
| 36 | + factory=CopyableFunctionWrapper, |
| 37 | + args=(_PredictForwardWrapper(),), |
| 38 | + ) |
| 39 | + |
| 40 | + predict_subclasses = Predict.__subclasses__() |
| 41 | + for predict_subclass in predict_subclasses: |
| 42 | + wrap_object( |
| 43 | + module=_DSPY_MODULE_NAME, |
| 44 | + name=predict_subclass.__name__ + ".forward", |
| 45 | + factory=CopyableFunctionWrapper, |
| 46 | + args=(_PredictForwardWrapper(),), |
| 47 | + ) |
| 48 | + |
| 49 | + wrap_object( |
| 50 | + module=_DSPY_MODULE_NAME, |
| 51 | + name="Retrieve.forward", |
| 52 | + factory=CopyableFunctionWrapper, |
| 53 | + args=(_GeneralDSPyWrapper("forward"),), |
| 54 | + ) |
| 55 | + |
| 56 | + wrap_object( |
| 57 | + module=_DSPY_MODULE_NAME, |
| 58 | + # At this time, dspy.Module does not have an abstract forward |
| 59 | + # method, but assumes that user-defined subclasses implement the |
| 60 | + # forward method and invokes that method using __call__. |
| 61 | + name="Module.__call__", |
| 62 | + factory=CopyableFunctionWrapper, |
| 63 | + args=(_GeneralDSPyWrapper("forward"),), |
| 64 | + ) |
| 65 | + |
| 66 | + # At this time, there is no common parent class for retriever models as |
| 67 | + # there is for language models. We instrument the retriever models on a |
| 68 | + # case-by-case basis. |
| 69 | + wrap_object( |
| 70 | + module=_DSP_MODULE_NAME, |
| 71 | + name="ColBERTv2.__call__", |
| 72 | + factory=CopyableFunctionWrapper, |
| 73 | + args=(_GeneralDSPyWrapper("__call__"),), |
| 74 | + ) |
| 75 | + |
| 76 | + |
| 77 | +class CopyableBoundFunctionWrapper(BoundFunctionWrapper): # type: ignore |
| 78 | + """ |
| 79 | + A bound function wrapper that can be copied and deep-copied. When used to |
| 80 | + wrap a class method, this allows the entire class to be copied and |
| 81 | + deep-copied. |
| 82 | +
|
| 83 | + For reference, see |
| 84 | + https://github.com/GrahamDumpleton/wrapt/issues/86#issuecomment-426161271 |
| 85 | + and |
| 86 | + https://wrapt.readthedocs.io/en/master/wrappers.html#custom-function-wrappers |
| 87 | + """ |
| 88 | + |
| 89 | + def __copy__(self) -> "CopyableBoundFunctionWrapper": |
| 90 | + return CopyableBoundFunctionWrapper(copy(self.__wrapped__), self._self_instance, self._self_wrapper) |
| 91 | + |
| 92 | + def __deepcopy__(self, memo: Dict[Any, Any]) -> "CopyableBoundFunctionWrapper": |
| 93 | + return CopyableBoundFunctionWrapper(deepcopy(self.__wrapped__, memo), self._self_instance, self._self_wrapper) |
| 94 | + |
| 95 | + |
| 96 | +class CopyableFunctionWrapper(FunctionWrapper): # type: ignore |
| 97 | + """ |
| 98 | + A function wrapper that can be copied and deep-copied. When used to wrap a |
| 99 | + class method, this allows the entire class to be copied and deep-copied. |
| 100 | +
|
| 101 | + For reference, see |
| 102 | + https://github.com/GrahamDumpleton/wrapt/issues/86#issuecomment-426161271 |
| 103 | + and |
| 104 | + https://wrapt.readthedocs.io/en/master/wrappers.html#custom-function-wrappers |
| 105 | + """ |
| 106 | + |
| 107 | + __bound_function_wrapper__ = CopyableBoundFunctionWrapper |
| 108 | + |
| 109 | + def __copy__(self) -> "CopyableFunctionWrapper": |
| 110 | + return CopyableFunctionWrapper(copy(self.__wrapped__), self._self_wrapper) |
| 111 | + |
| 112 | + def __deepcopy__(self, memo: Dict[Any, Any]) -> "CopyableFunctionWrapper": |
| 113 | + return CopyableFunctionWrapper(deepcopy(self.__wrapped__, memo), self._self_wrapper) |
| 114 | + |
| 115 | + |
| 116 | +class _GeneralDSPyWrapper: |
| 117 | + def __init__(self, method_name: str): |
| 118 | + self._method_name = method_name |
| 119 | + |
| 120 | + def __call__( |
| 121 | + self, |
| 122 | + wrapped: Callable[..., Any], |
| 123 | + instance: Any, |
| 124 | + args: Tuple[type, Any], |
| 125 | + kwargs: Mapping[str, Any], |
| 126 | + ) -> Any: |
| 127 | + span_name = instance.__class__.__name__ + "." + self._method_name |
| 128 | + return trace(name=span_name)(wrapped)(*args, **kwargs) |
| 129 | + |
| 130 | + |
| 131 | +class _PredictForwardWrapper: |
| 132 | + """ |
| 133 | + A wrapper for the Predict class to have a chain span for each prediction |
| 134 | + """ |
| 135 | + |
| 136 | + def __call__( |
| 137 | + self, |
| 138 | + wrapped: Callable[..., Any], |
| 139 | + instance: Any, |
| 140 | + args: Tuple[type, Any], |
| 141 | + kwargs: Mapping[str, Any], |
| 142 | + ) -> Any: |
| 143 | + from dspy import Predict |
| 144 | + |
| 145 | + # At this time, subclasses of Predict override the base class' forward |
| 146 | + # method and invoke the parent class' forward method from within the |
| 147 | + # overridden method. The forward method for both Predict and its |
| 148 | + # subclasses have been instrumented. To avoid creating duplicate spans |
| 149 | + # for a single invocation, we don't create a span for the base class' |
| 150 | + # forward method if the instance belongs to a proper subclass of Predict |
| 151 | + # with an overridden forward method. |
| 152 | + is_instance_of_predict_subclass = isinstance(instance, Predict) and (cls := instance.__class__) is not Predict |
| 153 | + has_overridden_forward_method = getattr(cls, "forward", None) is not getattr(Predict, "forward", None) |
| 154 | + wrapped_method_is_base_class_forward_method = wrapped.__qualname__ == Predict.forward.__qualname__ |
| 155 | + if is_instance_of_predict_subclass and has_overridden_forward_method and wrapped_method_is_base_class_forward_method: |
| 156 | + return wrapped(*args, **kwargs) |
| 157 | + else: |
| 158 | + return trace(name=_get_predict_span_name(instance))(wrapped)(*args, **kwargs) |
| 159 | + |
| 160 | + |
| 161 | +def _get_predict_span_name(instance: Any) -> str: |
| 162 | + """ |
| 163 | + Gets the name for the Predict span, which are the composition of a Predict |
| 164 | + class or subclass and a user-defined signature. An example name would be |
| 165 | + "Predict(UserDefinedSignature).forward". |
| 166 | + """ |
| 167 | + class_name = str(instance.__class__.__name__) |
| 168 | + if (signature := getattr(instance, "signature", None)) and (signature_name := _get_signature_name(signature)): |
| 169 | + return f"{class_name}({signature_name}).forward" |
| 170 | + return f"{class_name}.forward" |
| 171 | + |
| 172 | + |
| 173 | +def _get_signature_name(signature: Any) -> Optional[str]: |
| 174 | + """ |
| 175 | + A best-effort attempt to get the name of a signature. |
| 176 | + """ |
| 177 | + if ( |
| 178 | + # At the time of this writing, the __name__ attribute on signatures does |
| 179 | + # not return the user-defined class name, but __qualname__ does. |
| 180 | + qual_name := getattr(signature, "__qualname__", None) |
| 181 | + ) is None: |
| 182 | + return None |
| 183 | + return str(qual_name.split(".")[-1]) |
0 commit comments