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
375 lines (331 loc) · 12.9 KB
/
PythonPipeline.cs
File metadata and controls
375 lines (331 loc) · 12.9 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
using CSnakes.Runtime;
using CSnakes.Runtime.Python;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
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 int _progressRefresh;
private readonly IProgress<PipelineProgress> _progressCallback;
private PyObject _module;
private PyObject _functionLoad;
private PyObject _functionUnload;
private PyObject _functionCancel;
private PyObject _functionGenerate;
private PyObject _functionGetStepLatent;
private PyObject _functionGetLogs;
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;
_progressRefresh = 250;
_progressCallback = progressCallback;
_pipelineName = _configuration.Pipeline;
using (GIL.Acquire())
{
_logger?.LogInformation("[PythonPipeline] [ReloadModule] Importing pipeline module '{pipelineName}'.", _pipelineName);
_module = Import.ImportModule(_pipelineName);
BindFunctions();
}
_ = LoggingLoop(_progressRefresh);
}
/// <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>
/// 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>
/// Generate
/// </summary>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public Task<List<Tensor<float>>> GenerateAsync(PipelineOptions options, CancellationToken cancellationToken = default)
{
return Task.Run(() =>
{
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))
{
var results = new List<Tensor<float>>();
foreach (var pythonResult in pythonResults.AsBareEnumerable<IPyBuffer, PyObjectImporters.Buffer>())
{
results.Add(pythonResult.ToTensor().Normalize(Normalization.OneToOne));
}
return results;
}
}
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>
/// Gets the step latents.
/// </summary>
public Task<Tensor<float>> GetStepLatentAsync()
{
return Task.Run(() =>
{
using (GIL.Acquire())
{
try
{
_logger?.LogInformation("[PythonPipeline] [GetStepLatent] Fetching step latents.");
using (var pythonResult = _functionGetStepLatent.Call())
{
return pythonResult
.BareImportAs<IPyBuffer, PyObjectImporters.Buffer>()
.ToTensor();
}
}
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");
_functionUnload = _module.GetAttr("unload");
_functionCancel = _module.GetAttr("generateCancel");
_functionGenerate = _module.GetAttr("generate");
_functionGetStepLatent = _module.GetAttr("getStepLatent");
_functionGetLogs = _module.GetAttr("getLogs");
}
/// <summary>
/// Unbinds the functions.
/// </summary>
private void UnbindFunctions()
{
_functionLoad.Dispose();
_functionUnload.Dispose();
_functionCancel.Dispose();
_functionGenerate.Dispose();
_functionGetStepLatent.Dispose();
_functionGetLogs.Dispose();
}
/// <summary>
/// Logging loop.
/// </summary>
/// <param name="refreshRate">The refresh rate.</param>
private async Task LoggingLoop(int refreshRate)
{
while (_isRunning)
{
var logs = await GetLogsAsync();
foreach (var progress in LogParser.ParseLogs(logs))
{
if (progress == null)
continue;
if (!string.IsNullOrWhiteSpace(progress.Message))
_logger?.LogInformation("[PythonPipeline] [PythonRuntime] {Message}", progress.Message);
if (!string.IsNullOrWhiteSpace(progress.Process))
_progressCallback?.Report(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;
}
}
}