/
BlurFilter.java
453 lines (406 loc) · 19 KB
/
BlurFilter.java
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
/*
* Copyright 2022-2023 Juan Fumero
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.jjfumero;
import io.github.jjfumero.common.Options;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import uk.ac.manchester.tornado.api.GridScheduler;
import uk.ac.manchester.tornado.api.ImmutableTaskGraph;
import uk.ac.manchester.tornado.api.KernelContext;
import uk.ac.manchester.tornado.api.TaskGraph;
import uk.ac.manchester.tornado.api.TornadoExecutionPlan;
import uk.ac.manchester.tornado.api.WorkerGrid2D;
import uk.ac.manchester.tornado.api.annotations.Parallel;
import uk.ac.manchester.tornado.api.common.TornadoDevice;
import uk.ac.manchester.tornado.api.enums.DataTransferMode;
import uk.ac.manchester.tornado.api.runtime.TornadoRuntime;
import uk.ac.manchester.tornado.api.types.arrays.FloatArray;
import uk.ac.manchester.tornado.api.types.arrays.IntArray;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
/**
* Blur-Filter Algorithm taken from CUDA course CS344 from Udacity: {@url https://www.udacity.com/blog/2014/01/update-on-udacity-cs344-intro-to.html}
* This sample computes a blur filter from an JPEG image using different implementations:
*
* `tornado`: it runs with TornadoVM using the Loop Parallel API (using a hardware accelerator)
* `tornadoContext`: it runs with TornadoVM using the Parallel Kernel API (using a hardware accelerator)
* `mt`: it runs with JDK 8 Streams (multi-threaded version without TornadoVM)
* `seq`: it runs sequentially (no acceleration)
*
* Device Selection from command line:
*
* --device=<backendIndex>:<deviceIndex>
*
* To obtain the complete list of devices that TornadoVM can see:
*
* $ tornado --devices
*
* Example of how to run:
*
* a) Enabling TornadoVM
* <code>
* $ tornado -cp target/tornadovm-examples-1.0-SNAPSHOT.jar io.github.jjfumero.BlurFilter tornado
* </code>
*
* b) Running with the Java Streams version
*
* <code>
* tornado -cp target/tornadovm-examples-1.0-SNAPSHOT.jar io.github.jjfumero.BlurFilter mt
* </code>
*
*
* To run with JMH:
*
* <code>
* tornado -cp target/tornadovm-examples-1.0-SNAPSHOT.jar io.github.jjfumero.BlurFilter jmh
* </code>
*
*/
public class BlurFilter {
private static final int MAX_ITERATIONS = 10;
private BufferedImage image;
private Options.Implementation implementation;
private TaskGraph parallelFilter;
private TornadoExecutionPlan executionPlan;
public static final int FILTER_WIDTH = 31;
private static final String IMAGE_FILE = "./images/image.jpg";
int w;
int h;
IntArray redChannel;
IntArray greenChannel;
IntArray blueChannel;
IntArray alphaChannel;
IntArray redFilter;
IntArray greenFilter;
IntArray blueFilter;
FloatArray filter;
private GridScheduler grid;
public BlurFilter(Options.Implementation implementation, int backendIndex, int deviceIndex) {
this.implementation = implementation;
loadImage();
initData();
if (implementation == Options.Implementation.TORNADO_LOOP) {
// Tasks using the Loop Parallel API
parallelFilter = new TaskGraph("blur") //
.transferToDevice(DataTransferMode.FIRST_EXECUTION, redChannel, greenChannel, blueChannel, filter) //
.task("red", BlurFilter::compute, redChannel, redFilter, w, h, filter, FILTER_WIDTH) //
.task("green", BlurFilter::compute, greenChannel, greenFilter, w, h, filter, FILTER_WIDTH) //
.task("blue", BlurFilter::compute, blueChannel, blueFilter, w, h, filter, FILTER_WIDTH) //
.transferToHost(DataTransferMode.EVERY_EXECUTION, redFilter, greenFilter, blueFilter);
ImmutableTaskGraph immutableTaskGraph = parallelFilter.snapshot();
executionPlan = new TornadoExecutionPlan(immutableTaskGraph);
// Select the device
TornadoDevice device = TornadoExecutionPlan.getDevice(backendIndex, deviceIndex);
executionPlan.withDevice(device);
} else if (implementation == Options.Implementation.TORNADO_KERNEL) {
// Tasks using the Kernel API
KernelContext context = new KernelContext();
grid = new GridScheduler();
// This version might run slower, since thread block size can influence performance.
// TornadoVM implements a heuristic for thread block selection (available for loop-parallel API)
WorkerGrid2D worker = new WorkerGrid2D(w, h);
grid.setWorkerGrid("blur.red", worker);
grid.setWorkerGrid("blur.green", worker);
grid.setWorkerGrid("blur.blue", worker);
parallelFilter = new TaskGraph("blur") //
.transferToDevice(DataTransferMode.FIRST_EXECUTION, redChannel, greenChannel, blueChannel, filter) //
.task("red", BlurFilter::computeWithContext, redChannel, redFilter, w, h, filter, FILTER_WIDTH, context) //
.task("green", BlurFilter::computeWithContext, greenChannel, greenFilter, w, h, filter, FILTER_WIDTH, context) //
.task("blue", BlurFilter::computeWithContext, blueChannel, blueFilter, w, h, filter, FILTER_WIDTH, context) //
.transferToHost(DataTransferMode.EVERY_EXECUTION, redFilter, greenFilter, blueFilter);
executionPlan = new TornadoExecutionPlan(parallelFilter.snapshot());
executionPlan.withDevice(TornadoExecutionPlan.getDevice(backendIndex, deviceIndex)).withGridScheduler(grid);
}
}
public void loadImage() {
try {
image = ImageIO.read(new File(IMAGE_FILE));
} catch (IOException e) {
throw new RuntimeException("Input file not found: " + IMAGE_FILE);
}
}
private void initData() {
w = image.getWidth();
h = image.getHeight();
redChannel = new IntArray(w * h);
greenChannel = new IntArray(w * h);
blueChannel = new IntArray(w * h);
alphaChannel = new IntArray(w * h);
redFilter = new IntArray(w * h);
greenFilter = new IntArray(w * h);
blueFilter = new IntArray(w * h);
filter = new FloatArray(w * h);
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
filter.set(i * h + j, 1.f / (FILTER_WIDTH * FILTER_WIDTH));
}
}
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
int rgb = image.getRGB(i, j);
alphaChannel.set(i * h + j, (rgb >> 24) & 0xFF);
redChannel.set(i * h + j, (rgb >> 16) & 0xFF);
greenChannel.set(i * h + j, (rgb >> 8) & 0xFF);
blueChannel.set(i * h + j, (rgb & 0xFF));
}
}
}
private static void channelConvolutionSequential(IntArray channel, IntArray channelBlurred, final int numRows, final int numCols, FloatArray filter, final int filterWidth) {
for (int r = 0; r < numRows; r++) {
for (int c = 0; c < numCols; c++) {
float result = 0.0f;
for (int filter_r = -filterWidth / 2; filter_r <= filterWidth / 2; filter_r++) {
for (int filter_c = -filterWidth / 2; filter_c <= filterWidth / 2; filter_c++) {
int image_r = Math.min(Math.max(r + filter_r, 0), (numRows - 1));
int image_c = Math.min(Math.max(c + filter_c, 0), (numCols - 1));
float image_value = channel.get(image_r * numCols + image_c);
float filter_value = filter.get((filter_r + filterWidth / 2) * filterWidth + filter_c + filterWidth / 2);
result += image_value * filter_value;
}
}
int finalValue = result > 255 ? 255 : (int) result;
channelBlurred.set(r * numCols + c, finalValue);
}
}
}
private static void compute(IntArray channel, IntArray channelBlurred, final int numRows, final int numCols, FloatArray filter, final int filterWidth) {
for (@Parallel int r = 0; r < numRows; r++) {
for (@Parallel int c = 0; c < numCols; c++) {
float result = 0.0f;
for (int filter_r = -filterWidth / 2; filter_r <= filterWidth / 2; filter_r++) {
for (int filter_c = -filterWidth / 2; filter_c <= filterWidth / 2; filter_c++) {
int image_r = Math.min(Math.max(r + filter_r, 0), (numRows - 1));
int image_c = Math.min(Math.max(c + filter_c, 0), (numCols - 1));
float image_value = channel.get(image_r * numCols + image_c);
float filter_value = filter.get((filter_r + filterWidth / 2) * filterWidth + filter_c + filterWidth / 2);
result += image_value * filter_value;
}
}
int finalValue = result > 255 ? 255 : (int) result;
channelBlurred.set(r * numCols + c, finalValue);
}
}
}
private static void computeWithContext(IntArray channel, IntArray channelBlurred, final int numRows, final int numCols, FloatArray filter, final int filterWidth, KernelContext context) {
int r = context.globalIdx;
int c = context.globalIdy;
float result = 0.0f;
for (int filter_r = -filterWidth / 2; filter_r <= filterWidth / 2; filter_r++) {
for (int filter_c = -filterWidth / 2; filter_c <= filterWidth / 2; filter_c++) {
int image_r = Math.min(Math.max(r + filter_r, 0), (numRows - 1));
int image_c = Math.min(Math.max(c + filter_c, 0), (numCols - 1));
float image_value = channel.get(image_r * numCols + image_c);
float filter_value = filter.get((filter_r + filterWidth / 2) * filterWidth + filter_c + filterWidth / 2);
result += image_value * filter_value;
}
}
int finalValue = result > 255 ? 255 : (int) result;
channelBlurred.set(r * numCols + c, finalValue);
}
private static void computeWithParallelStreams(IntArray channel, IntArray channelBlurred, final int numRows, final int numCols, FloatArray filter, final int filterWidth) {
// For every pixel in the image
assert (filterWidth % 2 == 1);
IntStream.range(0, numRows).parallel().forEach(r -> {
IntStream.range(0, numCols).parallel().forEach(c -> {
float result = 0.0f;
for (int filter_r = -filterWidth / 2; filter_r <= filterWidth / 2; filter_r++) {
for (int filter_c = -filterWidth / 2; filter_c <= filterWidth / 2; filter_c++) {
int image_r = Math.min(Math.max(r + filter_r, 0), (numRows - 1));
int image_c = Math.min(Math.max(c + filter_c, 0), (numCols - 1));
float image_value = channel.get(image_r * numCols + image_c);
float filter_value = filter.get((filter_r + filterWidth / 2) * filterWidth + filter_c + filterWidth / 2);
result += image_value * filter_value;
}
}
int finalValue = result > 255 ? 255 : (int) result;
channelBlurred.set(r * numCols + c, finalValue);
});
});
}
private BufferedImage writeFile() {
setImageFromBuffers();
try {
File outputFile = new File( "./blur.jpeg");
ImageIO.write(image, "JPEG", outputFile);
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
private void setImageFromBuffers() {
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
Color c = new Color(redFilter.get(i * h + j), greenFilter.get(i * h + j), blueFilter.get(i * h + j), alphaChannel.get(i * h + j));
image.setRGB(i, j, c.getRGB());
}
}
}
private void sequentialComputation() {
for (int i = 0; i< MAX_ITERATIONS; i++) {
long start = System.nanoTime();
channelConvolutionSequential(redChannel, redFilter, w, h, filter, FILTER_WIDTH);
channelConvolutionSequential(greenChannel, greenFilter, w, h, filter, FILTER_WIDTH);
channelConvolutionSequential(blueChannel, blueFilter, w, h, filter, FILTER_WIDTH);
long end = System.nanoTime();
System.out.println(STR."Sequential Total time (ns) = \{end - start} -- seconds = \{(end - start) * 1e-9}");
}
}
private void sequentialComputationJHM() {
channelConvolutionSequential(redChannel, redFilter, w, h, filter, FILTER_WIDTH);
channelConvolutionSequential(greenChannel, greenFilter, w, h, filter, FILTER_WIDTH);
channelConvolutionSequential(blueChannel, blueFilter, w, h, filter, FILTER_WIDTH);
}
private void parallelStreams() {
for (int i = 0; i< MAX_ITERATIONS; i++) {
long start = System.nanoTime();
computeWithParallelStreams(redChannel, redFilter, w, h, filter, FILTER_WIDTH);
computeWithParallelStreams(greenChannel, greenFilter, w, h, filter, FILTER_WIDTH);
computeWithParallelStreams(blueChannel, blueFilter, w, h, filter, FILTER_WIDTH);
long end = System.nanoTime();
System.out.println(STR."Streams Total time (ns) = \{end - start} -- seconds = \{(end - start) * 1e-9}");
}
}
private void parallelStreamsJMH() {
computeWithParallelStreams(redChannel, redFilter, w, h, filter, FILTER_WIDTH);
computeWithParallelStreams(greenChannel, greenFilter, w, h, filter, FILTER_WIDTH);
computeWithParallelStreams(blueChannel, blueFilter, w, h, filter, FILTER_WIDTH);
}
private void runTornadoVM() {
for (int i = 0; i< MAX_ITERATIONS; i++) {
long start = System.nanoTime();
executionPlan.execute();
long end = System.nanoTime();
System.out.println(STR."TornadoVM Total Time (ns) = \{end - start} -- seconds = \{(end - start) * 1e-9}");
}
}
private void runTornadoVMJMH() {
executionPlan.execute();
}
private void runTornadoVMWithContext() {
for (int i = 0; i< MAX_ITERATIONS; i++) {
long start = System.nanoTime();
executionPlan.execute();
long end = System.nanoTime();
System.out.println(STR."TornadoVM(kernelAPI) Total Time (ns) = \{end - start} -- seconds = \{(end - start) * 1e-9}");
}
}
public void run() throws RunnerException {
switch (implementation) {
case SEQUENTIAL:
sequentialComputation();
break;
case MT:
parallelStreams();
break;
case TORNADO_LOOP:
runTornadoVM();
break;
case TORNADO_KERNEL:
runTornadoVMWithContext();
break;
case JMH:
runWithJMH();
break;
}
writeFile();
}
// Class to run with the JHM Java framework
@State(Scope.Thread)
public static class Benchmarking {
BlurFilter blurFilter;
@Setup(Level.Trial)
public void doSetup() {
// Select here the device to run (backendIndex, deviceIndex)
blurFilter = new BlurFilter(Options.Implementation.TORNADO_LOOP, 0, 3);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 2, time = 60, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 30, timeUnit = TimeUnit.SECONDS)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(1)
public void jvmSequential(Benchmarking state) {
state.blurFilter.sequentialComputationJHM();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 2, time = 60, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 30, timeUnit = TimeUnit.SECONDS)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(1)
public void jvmJavaStreams(Benchmarking state) {
state.blurFilter.parallelStreamsJMH();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 2, time = 60, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 30, timeUnit = TimeUnit.SECONDS)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(1)
public void runTornadoVM(Benchmarking state) {
state.blurFilter.runTornadoVMJMH();
}
}
private static void runWithJMH() throws RunnerException {
org.openjdk.jmh.runner.options.Options opt = new OptionsBuilder() //
.include(BlurFilter.class.getName() + ".*") //
.mode(Mode.AverageTime) //
.timeUnit(TimeUnit.NANOSECONDS) //
.warmupTime(TimeValue.seconds(60)) //
.warmupIterations(2) //
.measurementTime(TimeValue.seconds(30)) //
.measurementIterations(5) //
.forks(1) //
.build();
new Runner(opt).run();
}
public static void main(String[] args) throws RunnerException {
String version = "tornado"; // Use acceleration by default
int backendIndex = 0;
int deviceIndex = 0;
for (String arg : args) {
if (Options.isValid(arg)) {
version = arg;
}
if (arg.contains("device=")) {
String dev = arg.split("=")[1];
String[] backendDevice = dev.split(":");
backendIndex = Integer.parseInt(backendDevice[0]);
deviceIndex = Integer.parseInt(backendDevice[1]);
}
}
BlurFilter blurFilter = new BlurFilter(Options.getImplementation(version), backendIndex, deviceIndex);
blurFilter.run();
}
}