forked from TensorStack-AI/TensorStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonPipeline.cs
More file actions
466 lines (413 loc) · 16.4 KB
/
PythonPipeline.cs
File metadata and controls
466 lines (413 loc) · 16.4 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
using CSnakes.Runtime;
using CSnakes.Runtime.Python;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TensorStack.Common;
using TensorStack.Common.Tensor;
using TensorStack.Python.Common;
using TensorStack.Python.Config;
namespace TensorStack.Python
{
/// <summary>
/// PipelineProxy: Proxy between Python and C#
/// </summary>
public sealed class PythonPipeline : IDisposable
{
private readonly ILogger _logger;
private readonly string _pipelineName;
private readonly PipelineConfig _configuration;
private readonly IProgress<PipelineProgress> _progressCallback;
private PyObject _module;
private PyObject _functionLoad;
private PyObject _functionReload;
private PyObject _functionUnload;
private PyObject _functionDownload;
private PyObject _functionCancel;
private PyObject _functionGenerate;
private PyObject _functionGetLogs;
private PyObject _functionGetNotifications;
private bool _isRunning;
/// <summary>
/// Initializes a new instance of the <see cref="PythonPipeline"/> class.
/// </summary>
/// <param name="moduleName">Name of the module.</param>
/// <param name="logger">The logger.</param>
public PythonPipeline(PipelineConfig configuration, IProgress<PipelineProgress> progressCallback = default, ILogger logger = default)
{
_logger = logger;
_isRunning = true;
_configuration = configuration;
_progressCallback = progressCallback;
_pipelineName = _configuration.Pipeline;
using (GIL.Acquire())
{
_logger?.LogInformation("[PythonPipeline] [Load] Importing pipeline module '{pipelineName}'.", _pipelineName);
_module = Import.ImportModule(_pipelineName);
BindFunctions();
}
_ = LoggingLoop(50);
_ = NotificationLoop(25);
}
/// <summary>
/// Reloads the module.
/// </summary>
public void ReloadModule()
{
using (GIL.Acquire())
{
_logger?.LogInformation("[PythonPipeline] [ReloadModule] Reloading module.");
Import.ReloadModule(ref _module);
UnbindFunctions();
BindFunctions();
}
}
/// <summary>
/// Loads the proxy
/// </summary>
/// <param name="configuration">The configuration.</param>
public Task<bool> LoadAsync()
{
return Task.Run(() =>
{
using (GIL.Acquire())
{
try
{
_logger?.LogInformation("[PythonPipeline] [Load] Loading pipeline.");
var pipelineConfigDict = _configuration.ToPythonDictionary();
using (var pipelineConfig = PyObject.From(pipelineConfigDict))
using (var pythonResult = _functionLoad.Call(pipelineConfig))
{
return pythonResult.BareImportAs<bool, PyObjectImporters.Boolean>();
}
}
catch (PythonInvocationException ex)
{
throw HandlePythonException(ex);
}
}
});
}
/// <summary>
/// Reloads the pipeline.
/// </summary>
/// <param name="options">The options.</param>
/// <returns>Task<System.Boolean>.</returns>
public Task<bool> ReloadAsync(PipelineReloadOptions options)
{
return Task.Run(() =>
{
using (GIL.Acquire())
{
try
{
_logger?.LogInformation("[PythonPipeline] [Reload] Reloading pipeline.");
var configuration = _configuration with
{
ProcessType = options.ProcessType,
ControlNet = options.ControlNet,
LoraAdapters = options.LoraAdapters,
};
var pipelineConfigDict = configuration.ToPythonDictionary();
using (var pipelineConfig = PyObject.From(pipelineConfigDict))
using (var pythonResult = _functionReload.Call(pipelineConfig))
{
return pythonResult.BareImportAs<bool, PyObjectImporters.Boolean>();
}
}
catch (PythonInvocationException ex)
{
throw HandlePythonException(ex);
}
}
});
}
/// <summary>
/// Unload the proxy
/// </summary>
public Task<bool> UnloadAsync()
{
return Task.Run(() =>
{
using (GIL.Acquire())
{
try
{
_logger?.LogInformation("[PythonPipeline] [Unload] Unloading pipeline.");
using (var pythonResult = _functionUnload.Call())
{
return pythonResult.BareImportAs<bool, PyObjectImporters.Boolean>();
}
}
catch (PythonInvocationException ex)
{
throw HandlePythonException(ex);
}
}
});
}
/// <summary>
/// Download pipeline components
/// </summary>
public Task<bool> DownloadAsync()
{
return Task.Run(() =>
{
using (GIL.Acquire())
{
try
{
_logger?.LogInformation("[PythonPipeline] [Download] Downloading pipeline.");
var pipelineConfigDict = _configuration.ToPythonDictionary();
using (var pipelineConfig = PyObject.From(pipelineConfigDict))
using (var pythonResult = _functionDownload.Call(pipelineConfig))
{
return pythonResult.BareImportAs<bool, PyObjectImporters.Boolean>();
}
}
catch (PythonInvocationException ex)
{
throw HandlePythonException(ex);
}
}
});
}
/// <summary>
/// Generate
/// </summary>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public Task<IReadOnlyList<Tensor<float>>> GenerateAsync(PipelineOptions options, CancellationToken cancellationToken = default)
{
return Task.Run<IReadOnlyList<Tensor<float>>>(() =>
{
using (GIL.Acquire())
{
try
{
_logger?.LogInformation("[PythonPipeline] [Generate] Executing pipeline.");
cancellationToken.Register(() => GenerateCancelAsync(), true);
var inputTensors = GetInputData(options);
var controlInputTensors = GetControlInputData(options);
var inferenceOptionsDict = options.ToPythonDictionary();
using (var inferenceOptions = PyObject.From(inferenceOptionsDict))
using (var imageData = PyObject.From(inputTensors))
using (var controlNetData = PyObject.From(controlInputTensors))
using (var pythonResults = _functionGenerate.Call(inferenceOptions, imageData, controlNetData))
{
return pythonResults.AsBareEnumerable<IPyBuffer, PyObjectImporters.Buffer>()
.Select(x => x.ToTensor().Normalize(Normalization.OneToOne))
.ToList();
}
}
catch (PythonInvocationException ex)
{
throw HandlePythonException(ex);
}
}
});
}
/// <summary>
/// Gets the Notifications.
/// </summary>
public Task<IReadOnlyList<PipelineProgress>> GetNotificationsAsync()
{
return Task.Run<IReadOnlyList<PipelineProgress>>(() =>
{
using (GIL.Acquire())
{
try
{
using (var pythonResult = _functionGetNotifications.Call())
{
var pythonResults = pythonResult.BareImportAs<
IReadOnlyList<(string, IPyBuffer)>,
PyObjectImporters.List<(string, IPyBuffer),
PyObjectImporters.Tuple<string, IPyBuffer, PyObjectImporters.String, PyObjectImporters.Buffer>>>();
return pythonResults
.Select(x => PipelineProgress.Create(x.Item1, x.Item2.ToTensor()))
.Where(x => x?.Key != null)
.ToList();
}
}
catch (PythonInvocationException ex)
{
throw HandlePythonException(ex);
}
}
});
}
/// <summary>
/// Gets the logs.
/// </summary>
public Task<IReadOnlyList<string>> GetLogsAsync()
{
return Task.Run(() =>
{
using (GIL.Acquire())
{
try
{
using (var pythonResult = _functionGetLogs.Call())
{
return pythonResult.BareImportAs<IReadOnlyList<string>, PyObjectImporters.List<string, PyObjectImporters.String>>();
}
}
catch (PythonInvocationException ex)
{
throw HandlePythonException(ex);
}
}
});
}
/// <summary>
/// Cancel Generation
/// </summary>
/// <returns>Task.</returns>
private Task GenerateCancelAsync()
{
return Task.Run(() =>
{
using (GIL.Acquire())
{
try
{
_logger?.LogInformation("[PythonPipeline] [GenerateCancel] Canceling generation.");
using (var pythonResult = _functionCancel.Call())
{
return;
}
}
catch (PythonInvocationException ex)
{
throw HandlePythonException(ex);
}
}
});
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
_logger?.LogInformation("[PythonPipeline] [Dispose] Disposing pipeline.");
_isRunning = false;
UnbindFunctions();
_module.Dispose();
GC.SuppressFinalize(this);
}
/// <summary>
/// Binds the functions.
/// </summary>
private void BindFunctions()
{
_functionLoad = _module.GetAttr("load");
_functionReload = _module.GetAttr("reload");
_functionUnload = _module.GetAttr("unload");
_functionDownload = _module.GetAttr("download");
_functionCancel = _module.GetAttr("generateCancel");
_functionGenerate = _module.GetAttr("generate");
_functionGetLogs = _module.GetAttr("getLogs");
_functionGetNotifications = _module.GetAttr("getNotifications");
}
/// <summary>
/// Unbinds the functions.
/// </summary>
private void UnbindFunctions()
{
_functionLoad.Dispose();
_functionReload.Dispose();
_functionUnload.Dispose();
_functionDownload.Dispose();
_functionCancel.Dispose();
_functionGenerate.Dispose();
_functionGetLogs.Dispose();
_functionGetNotifications.Dispose();
}
/// <summary>
/// Logging loop.
/// </summary>
/// <param name="refreshRate">The refresh rate.</param>
private async Task LoggingLoop(int refreshRate)
{
while (_isRunning)
{
var logEntries = await GetLogsAsync();
foreach (var logEntry in LogParser.ParseLogs(logEntries).OrderBy(x => x.Timestamp))
{
if (string.IsNullOrWhiteSpace(logEntry?.Message))
continue;
_logger?.LogInformation("[PythonPipeline] [PythonRuntime] [{Timestamp}] {Message}", logEntry.Timestamp.ToString("hh:mm:ss:fff"), logEntry.Message);
}
await Task.Delay(refreshRate);
}
}
/// <summary>
/// Notification loop.
/// </summary>
/// <param name="refreshRate">The refresh rate.</param>
private async Task NotificationLoop(int refreshRate)
{
while (_isRunning)
{
var progressItems = await GetNotificationsAsync();
if (!progressItems.IsNullOrEmpty())
{
foreach (var progress in progressItems)
{
_progressCallback?.Report(progress);
_logger?.LogDebug("[PythonPipeline] [PythonRuntime] {Progress}", progress);
}
}
await Task.Delay(refreshRate);
}
}
/// <summary>
/// Handles the python exception.
/// </summary>
/// <param name="ex">The ex.</param>
/// <returns>Exception.</returns>
private Exception HandlePythonException(PythonInvocationException ex)
{
if (ex.InnerException is PythonRuntimeException pyex)
{
if (ex.InnerException.Message.Equals("Operation Canceled"))
return new OperationCanceledException();
_logger?.LogError(pyex, "[PythonPipeline] [PythonRuntime] {PythonExceptionType} exception occurred", ex.PythonExceptionType);
if (!pyex.PythonStackTrace.IsNullOrEmpty())
_logger?.LogError(string.Join(Environment.NewLine, pyex.PythonStackTrace));
return new Exception(pyex.Message, pyex);
}
_logger?.LogError(ex, "[PythonPipeline] [PythonRuntime] {PythonExceptionType} exception occurred", ex.PythonExceptionType);
return new Exception(ex.Message, ex);
}
private List<(float[], int[])> GetInputData(PipelineOptions options)
{
if (options.InputImages.IsNullOrEmpty())
return null;
var inputData = new List<(float[], int[])>();
foreach (var imageInput in options.InputImages)
{
var imageTensor = imageInput.GetChannels(3);
inputData.Add((imageTensor.Span.ToArray(), imageTensor.Dimensions.ToArray()));
}
return inputData;
}
private List<(float[], int[])> GetControlInputData(PipelineOptions options)
{
if (options.InputControlImages.IsNullOrEmpty())
return null;
var inputData = new List<(float[], int[])>();
foreach (var imageInput in options.InputControlImages)
{
var imageTensor = imageInput.GetChannels(3);
inputData.Add((imageTensor.Span.ToArray(), imageTensor.Dimensions.ToArray()));
}
return inputData;
}
}
}