Repository navigation
Expand file tree
/
Copy pathtracing.py
More file actions
271 lines (214 loc) · 8.93 KB
/
Copy pathtracing.py
File metadata and controls
271 lines (214 loc) · 8.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
"""Tracing helpers for local Hugging Face Transformers pipelines."""
from collections.abc import Callable, Iterator, Mapping
from braintrust.integrations.utils import _log_and_end_span, _log_error_and_end_span, _tensor_shape
from braintrust.logger import start_span as _bt_start_span
from braintrust.span_types import SpanTypeAttribute
_INSTRUMENTATION = "transformers-auto"
_PROVIDER = "huggingface"
_REQUEST_METADATA_KEYS = (
"temperature",
"top_p",
"stop",
"do_sample",
"top_k",
"repetition_penalty",
)
def start_span(*args, **kwargs):
internal = dict(kwargs.get("internal") or {})
internal.setdefault("instrumentation", _INSTRUMENTATION)
kwargs["internal"] = internal
return _bt_start_span(*args, **kwargs)
def _operation_name(task: str) -> str:
return f"huggingface.transformers.{task.replace('-', '_')}"
def _model_identifier(instance: object) -> str | None:
model = getattr(instance, "model", None)
config = getattr(model, "config", None)
for value in (
getattr(config, "_name_or_path", None),
getattr(config, "name_or_path", None),
getattr(config, "model_id", None),
getattr(model, "name", None),
):
if value:
return value
return None
def _metadata(instance: object, kwargs: dict[str, object], task: str) -> dict[str, object]:
metadata: dict[str, object] = {"provider": _PROVIDER}
model = _model_identifier(instance)
if model is not None:
metadata["model"] = model
metadata["task"] = task
device = getattr(instance, "device", None)
if device is not None:
metadata["device"] = device
pipeline_dtype = getattr(getattr(instance, "model", None), "dtype", None)
if pipeline_dtype is None:
pipeline_dtype = getattr(instance, "torch_dtype", None)
if pipeline_dtype is not None:
metadata["torch_dtype"] = pipeline_dtype
for key in _REQUEST_METADATA_KEYS:
if key in kwargs and kwargs[key] is not None:
metadata[key] = kwargs[key]
if kwargs.get("max_new_tokens") is not None:
metadata["max_tokens"] = kwargs["max_new_tokens"]
return metadata
def _first_call_input(args: tuple[object, ...], kwargs: dict[str, object]) -> object:
if args:
return args[0]
for key in ("inputs", "text_inputs"):
if key in kwargs:
return kwargs[key]
return None
def _is_chat(value: object) -> bool:
return bool(
isinstance(value, list)
and value
and all(
isinstance(message, Mapping) and isinstance(message.get("role"), str) and "content" in message
for message in value
)
)
def _message_input(value: object, *, allow_chat: bool = False) -> object:
if allow_chat and _is_chat(value):
return value
if allow_chat and isinstance(value, list) and value and all(_is_chat(item) for item in value):
return value
if isinstance(value, str):
return [{"role": "user", "content": value}]
if isinstance(value, list) and all(isinstance(item, str) for item in value):
return [[{"role": "user", "content": item}] for item in value]
return value
def _qa_message(question: object, context: object) -> dict[str, object]:
return {
"role": "user",
"content": f"Context:\n{context}\n\nQuestion:\n{question}",
}
def _question_answering_input(args: tuple[object, ...], kwargs: dict[str, object]) -> object:
question = kwargs.get("question")
context = kwargs.get("context")
if question is None and context is None and args:
value = args[0]
if isinstance(value, Mapping):
question = value.get("question")
context = value.get("context")
elif isinstance(value, list) and all(isinstance(item, Mapping) for item in value):
return [[_qa_message(item.get("question"), item.get("context"))] for item in value]
elif len(args) > 1:
question, context = args[0], args[1]
else:
return value
if isinstance(question, list) and isinstance(context, list):
return [[_qa_message(item_question, item_context)] for item_question, item_context in zip(question, context)]
if question is not None or context is not None:
return [_qa_message(question, context)]
return _first_call_input(args, kwargs)
def _input(task: str, args: tuple[object, ...], kwargs: dict[str, object]) -> object:
if task == "feature-extraction":
return _first_call_input(args, kwargs)
if task == "question-answering":
return _question_answering_input(args, kwargs)
return _message_input(_first_call_input(args, kwargs), allow_chat=task == "text-generation")
def _result_records(result: object) -> Iterator[Mapping[str, object]]:
if isinstance(result, Mapping):
yield result
elif isinstance(result, (list, tuple)):
for item in result:
yield from _result_records(item)
def _generated_content(record: Mapping[str, object], task: str) -> str | None:
if task == "summarization":
value = record.get("summary_text")
elif task.startswith("translation"):
value = record.get("translation_text")
elif task == "question-answering":
value = record.get("answer")
else:
value = record.get("generated_text")
if isinstance(value, str):
return value
if _is_chat(value):
content = value[-1].get("content")
return content if isinstance(content, str) else None
return None
def _choices(result: object, task: str) -> list[dict[str, object]] | None:
choices = []
for record in _result_records(result):
content = _generated_content(record, task)
if content is None:
continue
choices.append(
{
"index": len(choices),
"message": {"role": "assistant", "content": content},
}
)
return choices or None
def _output(task: str, result: object) -> object:
if task == "feature-extraction":
shape = _tensor_shape(result)
return {"shape": shape} if shape is not None else None
return _choices(result, task)
def _trace_pipeline_call(
wrapped: Callable[..., object],
instance: object,
args: tuple[object, ...],
kwargs: dict[str, object],
task: str,
) -> object:
if kwargs.get("streamer") is not None:
return wrapped(*args, **kwargs)
span_input = _input(task, args, kwargs)
metadata = _metadata(instance, kwargs, task)
span = start_span(
name=_operation_name(task),
type=SpanTypeAttribute.LLM,
input=span_input,
metadata=metadata,
)
try:
result = wrapped(*args, **kwargs)
except BaseException as error:
_log_error_and_end_span(span, error)
raise
output = _output(task, result)
_log_and_end_span(span, output=output)
return result
def _pipeline_call_for_task(
wrapped: Callable[..., object],
instance: object,
args: tuple[object, ...],
kwargs: dict[str, object],
expected_task: str,
) -> object:
task = getattr(instance, "task", None)
if task != expected_task:
return wrapped(*args, **kwargs)
return _trace_pipeline_call(wrapped, instance, args, kwargs, task)
def _text_generation_pipeline_call_wrapper(
wrapped: Callable[..., object], instance: object, args: tuple[object, ...], kwargs: dict[str, object]
) -> object:
return _pipeline_call_for_task(wrapped, instance, args, kwargs, "text-generation")
def _text2text_generation_pipeline_call_wrapper(
wrapped: Callable[..., object], instance: object, args: tuple[object, ...], kwargs: dict[str, object]
) -> object:
return _pipeline_call_for_task(wrapped, instance, args, kwargs, "text2text-generation")
def _summarization_pipeline_call_wrapper(
wrapped: Callable[..., object], instance: object, args: tuple[object, ...], kwargs: dict[str, object]
) -> object:
return _pipeline_call_for_task(wrapped, instance, args, kwargs, "summarization")
def _translation_pipeline_call_wrapper(
wrapped: Callable[..., object], instance: object, args: tuple[object, ...], kwargs: dict[str, object]
) -> object:
task = getattr(instance, "task", None)
# In addition to ``translation``, Transformers exposes language-specific
# task names such as ``translation_en_to_fr``.
if task != "translation" and not task.startswith("translation_"):
return wrapped(*args, **kwargs)
return _trace_pipeline_call(wrapped, instance, args, kwargs, task)
def _feature_extraction_pipeline_call_wrapper(
wrapped: Callable[..., object], instance: object, args: tuple[object, ...], kwargs: dict[str, object]
) -> object:
return _pipeline_call_for_task(wrapped, instance, args, kwargs, "feature-extraction")
def _question_answering_pipeline_call_wrapper(
wrapped: Callable[..., object], instance: object, args: tuple[object, ...], kwargs: dict[str, object]
) -> object:
return _pipeline_call_for_task(wrapped, instance, args, kwargs, "question-answering")