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

Upload extensions_built_in/sd_trainer/DiffusionTrainer.py with huggingface_hub

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