-
Notifications
You must be signed in to change notification settings - Fork 3
/
InstanceSegmentationRequest.php
333 lines (293 loc) · 10.3 KB
/
InstanceSegmentationRequest.php
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
<?php
namespace Biigle\Modules\Maia\Jobs;
use Biigle\Modules\Maia\GenericImage;
use Biigle\Modules\Maia\MaiaJob;
use Biigle\Volume;
use Exception;
use File;
use FileCache;
class InstanceSegmentationRequest extends JobRequest
{
/**
* Selected training proposals.
*
* @var array
*/
protected $trainingProposals;
/**
* URL of the volume for knowledge transfer (if any).
*
* @var string
*/
protected $knowledgeTransferVolumeUrl;
/**
* Filenames of the images of the knowledge transfer volume, indexed by their IDs.
*
* @var array
*/
protected $knowledgeTransferImages;
/**
* Create a new instance
*
* @param MaiaJob $job
*/
public function __construct(MaiaJob $job)
{
parent::__construct($job);
// Make sure to convert the annotations to arrays because it is more efficient
// and the GPU server cannot instantiate MaiaAnnotation objects (as they depend
// on biigle/core).
$this->trainingProposals = $this->bundleTrainingProposals($job);
if ($this->shouldUseKnowledgeTransfer()) {
$volume = Volume::find($this->jobParams['kt_volume_id']);
$this->knowledgeTransferVolumeUrl = $volume->url;
$this->knowledgeTransferImages = $volume->images()
->pluck('filename', 'id')
->toArray();
}
}
/**
* Execute the job
*/
public function handle()
{
$this->createTmpDir();
try {
$images = $this->getGenericImages();
if ($this->shouldUseKnowledgeTransfer()) {
$datasetImages = $this->getKnowledgeTransferImages();
} else {
$datasetImages = $images;
}
$datasetOutputPath = $this->generateDataset($datasetImages);
$trainingOutputPath = $this->performTraining($datasetOutputPath);
$this->performInference($images, $datasetOutputPath, $trainingOutputPath);
$annotations = $this->parseAnnotations($images);
$this->dispatchResponse($annotations);
} finally {
$this->cleanup();
}
}
/**
* Determine whether knowledge transfer should be performed in this job.
*
* @return bool
*/
protected function shouldUseKnowledgeTransfer()
{
return array_key_exists('training_data_method', $this->jobParams) && in_array($this->jobParams['training_data_method'], ['knowledge_transfer', 'area_knowledge_transfer']);
}
/**
* Bundle the training proposals to be sent to the GPU server.
*
* @param MaiaJob $job
*
* @return array
*/
protected function bundleTrainingProposals(MaiaJob $job)
{
return $job->trainingProposals()
->selected()
->select('image_id', 'points')
->get()
->groupBy('image_id')
->map(function ($proposals) {
return $proposals->pluck('points')->map(function ($proposal) {
// The circles of the proposals are drawn by OpenCV and this expects
// integers. As we can shave off a few bytes of job payload this
// way, we parse the coordinates here instead of in the Python
// script.
return array_map(function ($value) {
return intval(round($value));
}, $proposal);
});
})
->toArray();
}
/**
* Generate the training dataset for Mask R-CNN.
*
* @param array $images GenericImage instances.
*
* @return string Path to the JSON output file.
*/
protected function generateDataset($images)
{
$outputPath = "{$this->tmpDir}/output-dataset.json";
// All images that contain selected training proposals.
$relevantImages = array_filter($images, function ($image) {
return array_key_exists($image->getId(), $this->trainingProposals);
});
FileCache::batch($relevantImages, function ($images, $paths) use ($outputPath) {
$imagesMap = $this->buildImagesMap($images, $paths);
$inputPath = $this->createDatasetJson($imagesMap, $outputPath);
$script = config('maia.mrcnn_dataset_script');
$this->python("{$script} {$inputPath}", 'dataset-log.txt');
});
return $outputPath;
}
/**
* Create the JSON file that is the input to the dataset generation script.
*
* @param array $imagesMap Map from image IDs to cached file paths.
* @param string $outputJsonPath Path to the output file of the script.
*
* @return string Input JSON file path.
*/
protected function createDatasetJson($imagesMap, $outputJsonPath)
{
$path = "{$this->tmpDir}/input-dataset.json";
$content = [
'images' => $imagesMap,
'tmp_dir' => $this->tmpDir,
'available_bytes' => intval(config('maia.available_bytes')),
'max_workers' => intval(config('maia.max_workers')),
'training_proposals' => $this->trainingProposals,
'output_path' => $outputJsonPath,
];
if ($this->shouldUseKnowledgeTransfer()) {
$content['kt_scale_factors'] = $this->jobParams['kt_scale_factors'];
}
File::put($path, json_encode($content, JSON_UNESCAPED_SLASHES));
return $path;
}
/**
* Perform training of Mask R-CNN.
*
* @param string $datasetOutputPath Path to the JSON output of the dataset generator.
*
* @return string Path to the JSON output file of the training script.
*/
protected function performTraining($datasetOutputPath)
{
$outputPath = "{$this->tmpDir}/output-training.json";
$this->maybeDownloadCocoModel();
$inputPath = $this->createTrainingJson($outputPath);
$script = config('maia.mrcnn_training_script');
$this->python("{$script} {$inputPath} {$datasetOutputPath}", 'training-log.txt');
return $outputPath;
}
/**
* Downloads the Mask R-CNN COCO pretrained weights if they weren't downloaded yet.
*/
protected function maybeDownloadCocoModel()
{
$path = config('maia.coco_model_path');
if (!File::exists($path)) {
$this->ensureDirectory(dirname($path));
$url = config('maia.coco_model_url');
$success = @copy($url, $path);
if (!$success) {
throw new Exception("Failed to download Mask R-CNN weights from '{$url}'.");
}
}
}
/**
* Create the JSON file that is the input to the training script.
*
* @param string $outputJsonPath Path to the output file of the script.
*
* @return string Input JSON file path.
*/
protected function createTrainingJson($outputJsonPath)
{
$path = "{$this->tmpDir}/input-training.json";
$content = [
'is_train_scheme' => $this->jobParams['is_train_scheme'],
'tmp_dir' => $this->tmpDir,
'available_bytes' => intval(config('maia.available_bytes')),
'max_workers' => intval(config('maia.max_workers')),
'output_path' => $outputJsonPath,
'coco_model_path' => config('maia.coco_model_path'),
];
File::put($path, json_encode($content, JSON_UNESCAPED_SLASHES));
return $path;
}
/**
* Perform inference with the trained Mask R-CNN.
*
* @param array $images GenericImage instances.
* @param string $datasetOutputPath Path to the JSON output of the dataset generator.
* @param string $trainingOutputPath Path to the JSON output of the training script.
*/
protected function performInference($images, $datasetOutputPath, $trainingOutputPath)
{
FileCache::batch($images, function ($images, $paths) use ($datasetOutputPath, $trainingOutputPath) {
$imagesMap = $this->buildImagesMap($images, $paths);
$inputPath = $this->createInferenceJson($imagesMap);
$script = config('maia.mrcnn_inference_script');
$this->python("{$script} {$inputPath} {$datasetOutputPath} {$trainingOutputPath}", 'inference-log.txt');
});
}
/**
* Create the JSON file that is the input to the inference script.
*
* @param array $imagesMap Map from image IDs to cached file paths.
*
* @return string Input JSON file path.
*/
protected function createInferenceJson($imagesMap)
{
$path = "{$this->tmpDir}/input-inference.json";
$content = [
'images' => $imagesMap,
'tmp_dir' => $this->tmpDir,
'available_bytes' => intval(config('maia.available_bytes')),
'max_workers' => intval(config('maia.max_workers')),
];
File::put($path, json_encode($content, JSON_UNESCAPED_SLASHES));
return $path;
}
/**
* Build the map from image ID to path of the cached image file.
*
* @param array $images GenericImage instances.
* @param array $paths Cached image file paths.
*
* @return array
*/
protected function buildImagesMap($images, $paths)
{
$imagesMap = [];
foreach ($images as $index => $image) {
$imagesMap[$image->getId()] = $paths[$index];
}
return $imagesMap;
}
/**
* Dispatch the job to store the instance segmentation results.
*
* @param array $annotations
*/
protected function dispatchResponse($annotations)
{
$this->dispatch(new InstanceSegmentationResponse($this->jobId, $annotations));
}
/**
* {@inheritdoc}
*/
protected function dispatchFailure(Exception $e)
{
$this->dispatch(new InstanceSegmentationFailure($this->jobId, $e));
}
/**
* {@inheritdoc}
*/
protected function getTmpDirPath()
{
return parent::getTmpDirPath()."-instance-segmentation";
}
/**
* Create GenericImage instances for the images of the knowledge transfer volume.
*
* @return array
*/
protected function getKnowledgeTransferImages()
{
$images = [];
foreach ($this->knowledgeTransferImages as $id => $filename) {
$images[$id] = new GenericImage($id, "{$this->knowledgeTransferVolumeUrl}/{$filename}");
}
return $images;
}
}