Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
automatic1111
GitHub Repository: automatic1111/stable-diffusion-webui
Path: blob/master/modules/call_queue.py
3055 views
1
import os.path
2
from functools import wraps
3
import html
4
import time
5
6
from modules import shared, progress, errors, devices, fifo_lock, profiling
7
8
queue_lock = fifo_lock.FIFOLock()
9
10
11
def wrap_queued_call(func):
12
def f(*args, **kwargs):
13
with queue_lock:
14
res = func(*args, **kwargs)
15
16
return res
17
18
return f
19
20
21
def wrap_gradio_gpu_call(func, extra_outputs=None):
22
@wraps(func)
23
def f(*args, **kwargs):
24
25
# if the first argument is a string that says "task(...)", it is treated as a job id
26
if args and type(args[0]) == str and args[0].startswith("task(") and args[0].endswith(")"):
27
id_task = args[0]
28
progress.add_task_to_queue(id_task)
29
else:
30
id_task = None
31
32
with queue_lock:
33
shared.state.begin(job=id_task)
34
progress.start_task(id_task)
35
36
try:
37
res = func(*args, **kwargs)
38
progress.record_results(id_task, res)
39
finally:
40
progress.finish_task(id_task)
41
42
shared.state.end()
43
44
return res
45
46
return wrap_gradio_call(f, extra_outputs=extra_outputs, add_stats=True)
47
48
49
def wrap_gradio_call(func, extra_outputs=None, add_stats=False):
50
@wraps(func)
51
def f(*args, **kwargs):
52
try:
53
res = func(*args, **kwargs)
54
finally:
55
shared.state.skipped = False
56
shared.state.interrupted = False
57
shared.state.stopping_generation = False
58
shared.state.job_count = 0
59
shared.state.job = ""
60
return res
61
62
return wrap_gradio_call_no_job(f, extra_outputs, add_stats)
63
64
65
def wrap_gradio_call_no_job(func, extra_outputs=None, add_stats=False):
66
@wraps(func)
67
def f(*args, extra_outputs_array=extra_outputs, **kwargs):
68
run_memmon = shared.opts.memmon_poll_rate > 0 and not shared.mem_mon.disabled and add_stats
69
if run_memmon:
70
shared.mem_mon.monitor()
71
t = time.perf_counter()
72
73
try:
74
res = list(func(*args, **kwargs))
75
except Exception as e:
76
# When printing out our debug argument list,
77
# do not print out more than a 100 KB of text
78
max_debug_str_len = 131072
79
message = "Error completing request"
80
arg_str = f"Arguments: {args} {kwargs}"[:max_debug_str_len]
81
if len(arg_str) > max_debug_str_len:
82
arg_str += f" (Argument list truncated at {max_debug_str_len}/{len(arg_str)} characters)"
83
errors.report(f"{message}\n{arg_str}", exc_info=True)
84
85
if extra_outputs_array is None:
86
extra_outputs_array = [None, '']
87
88
error_message = f'{type(e).__name__}: {e}'
89
res = extra_outputs_array + [f"<div class='error'>{html.escape(error_message)}</div>"]
90
91
devices.torch_gc()
92
93
if not add_stats:
94
return tuple(res)
95
96
elapsed = time.perf_counter() - t
97
elapsed_m = int(elapsed // 60)
98
elapsed_s = elapsed % 60
99
elapsed_text = f"{elapsed_s:.1f} sec."
100
if elapsed_m > 0:
101
elapsed_text = f"{elapsed_m} min. "+elapsed_text
102
103
if run_memmon:
104
mem_stats = {k: -(v//-(1024*1024)) for k, v in shared.mem_mon.stop().items()}
105
active_peak = mem_stats['active_peak']
106
reserved_peak = mem_stats['reserved_peak']
107
sys_peak = mem_stats['system_peak']
108
sys_total = mem_stats['total']
109
sys_pct = sys_peak/max(sys_total, 1) * 100
110
111
toltip_a = "Active: peak amount of video memory used during generation (excluding cached data)"
112
toltip_r = "Reserved: total amount of video memory allocated by the Torch library "
113
toltip_sys = "System: peak amount of video memory allocated by all running programs, out of total capacity"
114
115
text_a = f"<abbr title='{toltip_a}'>A</abbr>: <span class='measurement'>{active_peak/1024:.2f} GB</span>"
116
text_r = f"<abbr title='{toltip_r}'>R</abbr>: <span class='measurement'>{reserved_peak/1024:.2f} GB</span>"
117
text_sys = f"<abbr title='{toltip_sys}'>Sys</abbr>: <span class='measurement'>{sys_peak/1024:.1f}/{sys_total/1024:g} GB</span> ({sys_pct:.1f}%)"
118
119
vram_html = f"<p class='vram'>{text_a}, <wbr>{text_r}, <wbr>{text_sys}</p>"
120
else:
121
vram_html = ''
122
123
if shared.opts.profiling_enable and os.path.exists(shared.opts.profiling_filename):
124
profiling_html = f"<p class='profile'> [ <a href='{profiling.webpath()}' download>Profile</a> ] </p>"
125
else:
126
profiling_html = ''
127
128
# last item is always HTML
129
res[-1] += f"<div class='performance'><p class='time'>Time taken: <wbr><span class='measurement'>{elapsed_text}</span></p>{vram_html}{profiling_html}</div>"
130
131
return tuple(res)
132
133
return f
134
135
136