comdoleger commited on
Commit
cf4db3d
·
verified ·
1 Parent(s): 11035ed

Upload extensions_built_in/sd_trainer/UITrainer.py with huggingface_hub

Browse files
extensions_built_in/sd_trainer/UITrainer.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ import os
3
+ import sqlite3
4
+ import asyncio
5
+ import concurrent.futures
6
+ from extensions_built_in.sd_trainer.SDTrainer import SDTrainer
7
+ from typing import Literal, Optional
8
+ import threading
9
+ import time
10
+ import signal
11
+
12
+ AITK_Status = Literal["running", "stopped", "error", "completed"]
13
+
14
+
15
+ class UITrainer(SDTrainer):
16
+ def __init__(self, process_id: int, job, config: OrderedDict, **kwargs):
17
+ super(UITrainer, self).__init__(process_id, job, config, **kwargs)
18
+ self.sqlite_db_path = self.config.get("sqlite_db_path", "./aitk_db.db")
19
+ if not os.path.exists(self.sqlite_db_path):
20
+ raise Exception(
21
+ f"SQLite database not found at {self.sqlite_db_path}")
22
+ print(f"Using SQLite database at {self.sqlite_db_path}")
23
+ self.job_id = os.environ.get("AITK_JOB_ID", None)
24
+ self.job_id = self.job_id.strip() if self.job_id is not None else None
25
+ print(f"Job ID: \"{self.job_id}\"")
26
+ if self.job_id is None:
27
+ raise Exception("AITK_JOB_ID not set")
28
+ self.is_stopping = False
29
+ # Create a thread pool for database operations
30
+ self.thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)
31
+ # Track all async tasks
32
+ self._async_tasks = []
33
+ # Initialize the status
34
+ self._run_async_operation(self._update_status("running", "Starting"))
35
+ self._stop_watcher_started = False
36
+ # self.start_stop_watcher(interval_sec=2.0)
37
+
38
+ def start_stop_watcher(self, interval_sec: float = 5.0):
39
+ """
40
+ Start a daemon thread that periodically checks should_stop()
41
+ and terminates the process immediately when triggered.
42
+ """
43
+ if getattr(self, "_stop_watcher_started", False):
44
+ return
45
+ self._stop_watcher_started = True
46
+ t = threading.Thread(
47
+ target=self._stop_watcher_thread, args=(interval_sec,), daemon=True
48
+ )
49
+ t.start()
50
+
51
+ def _stop_watcher_thread(self, interval_sec: float):
52
+ while True:
53
+ try:
54
+ if self.should_stop():
55
+ # Mark and update status (non-blocking; uses existing infra)
56
+ self.is_stopping = True
57
+ self._run_async_operation(
58
+ self._update_status("stopped", "Job stopped (remote)")
59
+ )
60
+ # Best-effort flush pending async ops
61
+ try:
62
+ asyncio.run(self.wait_for_all_async())
63
+ except RuntimeError:
64
+ pass
65
+ # Try to stop DB thread pool quickly
66
+ try:
67
+ self.thread_pool.shutdown(wait=False, cancel_futures=True)
68
+ except TypeError:
69
+ self.thread_pool.shutdown(wait=False)
70
+ print("")
71
+ print("****************************************************")
72
+ print(" Stop signal received; terminating process. ")
73
+ print("****************************************************")
74
+ os.kill(os.getpid(), signal.SIGINT)
75
+ time.sleep(interval_sec)
76
+ except Exception:
77
+ time.sleep(interval_sec)
78
+
79
+ def _run_async_operation(self, coro):
80
+ """Helper method to run an async coroutine and track the task."""
81
+ try:
82
+ loop = asyncio.get_event_loop()
83
+ except RuntimeError:
84
+ # No event loop exists, create a new one
85
+ loop = asyncio.new_event_loop()
86
+ asyncio.set_event_loop(loop)
87
+
88
+ # Create a task and track it
89
+ if loop.is_running():
90
+ task = asyncio.run_coroutine_threadsafe(coro, loop)
91
+ self._async_tasks.append(asyncio.wrap_future(task))
92
+ else:
93
+ task = loop.create_task(coro)
94
+ self._async_tasks.append(task)
95
+ loop.run_until_complete(task)
96
+
97
+ async def _execute_db_operation(self, operation_func):
98
+ """Execute a database operation in a separate thread to avoid blocking."""
99
+ loop = asyncio.get_event_loop()
100
+ return await loop.run_in_executor(self.thread_pool, operation_func)
101
+
102
+ def _db_connect(self):
103
+ """Create a new connection for each operation to avoid locking."""
104
+ conn = sqlite3.connect(self.sqlite_db_path, timeout=10.0)
105
+ conn.isolation_level = None # Enable autocommit mode
106
+ return conn
107
+
108
+ def should_stop(self):
109
+ def _check_stop():
110
+ with self._db_connect() as conn:
111
+ cursor = conn.cursor()
112
+ cursor.execute(
113
+ "SELECT stop FROM Job WHERE id = ?", (self.job_id,))
114
+ stop = cursor.fetchone()
115
+ return False if stop is None else stop[0] == 1
116
+
117
+ return _check_stop()
118
+
119
+ def maybe_stop(self):
120
+ if self.should_stop():
121
+ self._run_async_operation(
122
+ self._update_status("stopped", "Job stopped"))
123
+ self.is_stopping = True
124
+ raise Exception("Job stopped")
125
+
126
+ async def _update_key(self, key, value):
127
+ if not self.accelerator.is_main_process:
128
+ return
129
+
130
+ def _do_update():
131
+ with self._db_connect() as conn:
132
+ cursor = conn.cursor()
133
+ cursor.execute("BEGIN IMMEDIATE")
134
+ try:
135
+ # Convert the value to string if it's not already
136
+ if isinstance(value, str):
137
+ value_to_insert = value
138
+ else:
139
+ value_to_insert = str(value)
140
+
141
+ # Use parameterized query for both the column name and value
142
+ update_query = f"UPDATE Job SET {key} = ? WHERE id = ?"
143
+ cursor.execute(
144
+ update_query, (value_to_insert, self.job_id))
145
+ finally:
146
+ cursor.execute("COMMIT")
147
+
148
+ await self._execute_db_operation(_do_update)
149
+
150
+ def update_step(self):
151
+ """Non-blocking update of the step count."""
152
+ if self.accelerator.is_main_process:
153
+ self._run_async_operation(self._update_key("step", self.step_num))
154
+
155
+ def update_db_key(self, key, value):
156
+ """Non-blocking update a key in the database."""
157
+ if self.accelerator.is_main_process:
158
+ self._run_async_operation(self._update_key(key, value))
159
+
160
+ async def _update_status(self, status: AITK_Status, info: Optional[str] = None):
161
+ if not self.accelerator.is_main_process:
162
+ return
163
+
164
+ def _do_update():
165
+ with self._db_connect() as conn:
166
+ cursor = conn.cursor()
167
+ cursor.execute("BEGIN IMMEDIATE")
168
+ try:
169
+ if info is not None:
170
+ cursor.execute(
171
+ "UPDATE Job SET status = ?, info = ? WHERE id = ?",
172
+ (status, info, self.job_id)
173
+ )
174
+ else:
175
+ cursor.execute(
176
+ "UPDATE Job SET status = ? WHERE id = ?",
177
+ (status, self.job_id)
178
+ )
179
+ finally:
180
+ cursor.execute("COMMIT")
181
+
182
+ await self._execute_db_operation(_do_update)
183
+
184
+ def update_status(self, status: AITK_Status, info: Optional[str] = None):
185
+ """Non-blocking update of status."""
186
+ if self.accelerator.is_main_process:
187
+ self._run_async_operation(self._update_status(status, info))
188
+
189
+ async def wait_for_all_async(self):
190
+ """Wait for all tracked async operations to complete."""
191
+ if not self._async_tasks:
192
+ return
193
+
194
+ try:
195
+ await asyncio.gather(*self._async_tasks)
196
+ except Exception as e:
197
+ pass
198
+ finally:
199
+ # Clear the task list after completion
200
+ self._async_tasks.clear()
201
+
202
+ def on_error(self, e: Exception):
203
+ super(UITrainer, self).on_error(e)
204
+ if self.accelerator.is_main_process and not self.is_stopping:
205
+ self.update_status("error", str(e))
206
+ self.update_db_key("step", self.last_save_step)
207
+ asyncio.run(self.wait_for_all_async())
208
+ self.thread_pool.shutdown(wait=True)
209
+
210
+ def handle_timing_print_hook(self, timing_dict):
211
+ if "train_loop" not in timing_dict:
212
+ print("train_loop not found in timing_dict", timing_dict)
213
+ return
214
+ seconds_per_iter = timing_dict["train_loop"]
215
+ # determine iter/sec or sec/iter
216
+ if seconds_per_iter < 1:
217
+ iters_per_sec = 1 / seconds_per_iter
218
+ self.update_db_key("speed_string", f"{iters_per_sec:.2f} iter/sec")
219
+ else:
220
+ self.update_db_key(
221
+ "speed_string", f"{seconds_per_iter:.2f} sec/iter")
222
+
223
+ def done_hook(self):
224
+ super(UITrainer, self).done_hook()
225
+ self.update_status("completed", "Training completed")
226
+ # Wait for all async operations to finish before shutting down
227
+ asyncio.run(self.wait_for_all_async())
228
+ self.thread_pool.shutdown(wait=True)
229
+
230
+ def end_step_hook(self):
231
+ super(UITrainer, self).end_step_hook()
232
+ self.update_step()
233
+ self.maybe_stop()
234
+
235
+ def hook_before_model_load(self):
236
+ super().hook_before_model_load()
237
+ self.maybe_stop()
238
+ self.update_status("running", "Loading model")
239
+
240
+ def before_dataset_load(self):
241
+ super().before_dataset_load()
242
+ self.maybe_stop()
243
+ self.update_status("running", "Loading dataset")
244
+
245
+ def hook_before_train_loop(self):
246
+ super().hook_before_train_loop()
247
+ self.maybe_stop()
248
+ self.update_step()
249
+ self.update_status("running", "Training")
250
+ self.timer.add_after_print_hook(self.handle_timing_print_hook)
251
+
252
+ def status_update_hook_func(self, string):
253
+ self.update_status("running", string)
254
+
255
+ def hook_after_sd_init_before_load(self):
256
+ super().hook_after_sd_init_before_load()
257
+ self.maybe_stop()
258
+ self.sd.add_status_update_hook(self.status_update_hook_func)
259
+
260
+ def sample_step_hook(self, img_num, total_imgs):
261
+ super().sample_step_hook(img_num, total_imgs)
262
+ self.maybe_stop()
263
+ self.update_status(
264
+ "running", f"Generating images - {img_num + 1}/{total_imgs}")
265
+
266
+ def sample(self, step=None, is_first=False):
267
+ self.maybe_stop()
268
+ total_imgs = len(self.sample_config.prompts)
269
+ self.update_status("running", f"Generating images - 0/{total_imgs}")
270
+ super().sample(step, is_first)
271
+ self.maybe_stop()
272
+ self.update_status("running", "Training")
273
+
274
+ def save(self, step=None):
275
+ self.maybe_stop()
276
+ self.update_status("running", "Saving model")
277
+ super().save(step)
278
+ self.maybe_stop()
279
+ self.update_status("running", "Training")