-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathllm_timer_wrapper.py
115 lines (92 loc) · 3.11 KB
/
llm_timer_wrapper.py
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
# -*- coding: utf-8 -*-
"""
Filename: llm_timer_wrapper.py
Author: Iliya Vereshchagin
Copyright (c) 2023. All rights reserved.
Created: 21.11.2023
Last Modified: 21.11.2023
Description:
This file contains the decorator for measuring time metrics of function execution.
"""
import time
class TimeMetricsWrapperSync:
"""Decorator for measuring time metrics of function execution"""
def __init__(self, function):
"""
Initialize TimeMetricsWrapper class.
:param function: The function to measure.
:type function: function
"""
self.function = function
def __call__(self, prompt, model=None):
"""
Call the function and measure the time it takes to execute.
:param prompt: The prompt to use for the function.
:type prompt: str
:param model: The model to use for the function.
:type model: str
:return: The metrics of the function.
:rtype: dict
"""
start_time = time.time()
if model:
result = self.function(prompt, model)
else:
result = self.function(prompt)
end_time = time.time()
elapsed_time = end_time - start_time
words = len(result.split())
chars = len(result)
tokens = len(result) // 3
word_speed = elapsed_time / words if words else 0
char_speed = elapsed_time / chars if chars else 0
token_speed = elapsed_time / tokens if tokens else 0
metrix = {
"elapsed_time": elapsed_time,
"words": words,
"chars": chars,
"tokens": tokens,
"word_speed": word_speed,
"char_speed": char_speed,
"token_speed": token_speed,
"results": result,
}
return metrix
class TimeMetricsWrapperAsync:
"""Decorator for measuring time metrics of function execution"""
def __init__(self, function):
"""
Initialize TimeMetricsWrapper class.
:param function: The function to measure.
:type function: function
"""
self.function = function
async def __call__(self, prompt):
"""
Call the function and measure the time it takes to execute.
:param prompt: The prompt to use for the function.
:type prompt: str
:return: The metrics of the function.
:rtype: dict
"""
start_time = time.time()
result = await self.function(prompt)
end_time = time.time()
elapsed_time = end_time - start_time
words = len(result.split())
chars = len(result)
tokens = len(result) // 3
word_speed = elapsed_time / words if words else 0
char_speed = elapsed_time / chars if chars else 0
token_speed = elapsed_time / tokens if tokens else 0
metrix = {
"elapsed_time": elapsed_time,
"words": words,
"chars": chars,
"tokens": tokens,
"word_speed": word_speed,
"char_speed": char_speed,
"token_speed": token_speed,
"results": result,
}
return metrix