-
Notifications
You must be signed in to change notification settings - Fork 18
/
benchmarks.scala
545 lines (444 loc) · 17.4 KB
/
benchmarks.scala
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
package com.thoughtworks.compute
import java.util.concurrent.TimeUnit
import com.thoughtworks.compute.OpenCL.Exceptions.DeviceNotFound
import com.thoughtworks.feature.Factory
import com.thoughtworks.future._
import com.thoughtworks.continuation._
import com.thoughtworks.raii.asynchronous._
import com.thoughtworks.raii.covariant._
import com.thoughtworks.tryt.covariant._
import com.typesafe.scalalogging.StrictLogging
import org.lwjgl.opencl.CL10
import org.nd4j.linalg.api.ndarray.INDArray
import org.nd4j.linalg.convolution.Convolution
import org.nd4j.linalg.factory.Nd4j
import org.nd4j.linalg.ops.transforms.Transforms
import org.openjdk.jmh.annotations._
import scalaz.syntax.all._
import scalaz.std.list._
import scala.util.Try
object benchmarks {
trait TensorState {
@Param(Array("GPU"))
protected var tensorDeviceType: String = _
@Param(Array("5"))
protected var numberOfCommandQueuesPerDevice: Int = _
trait BenchmarkTensors
extends StrictLogging
with Tensors.UnsafeMathOptimizations
with Tensors.SuppressWarnings
with OpenCL.LogContextNotification
with OpenCL.UseAllDevicesByType
with OpenCL.GlobalExecutionContext
with OpenCL.CommandQueuePool
with OpenCL.DontReleaseEventTooEarly
with OpenCL.SynchronizedCreatingKernel
with OpenCL.HandleEventInExecutionContextForIntelAndAMDPlatform
with Tensors.WangHashingRandomNumberGenerator {
protected val deviceType: Int =
classOf[CL10].getField(s"CL_DEVICE_TYPE_$tensorDeviceType").get(null).asInstanceOf[Int]
protected val numberOfCommandQueuesPerDevice: Int = TensorState.this.numberOfCommandQueuesPerDevice
}
}
@Threads(value = Threads.MAX)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Timeout(time = 2, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
class MatrixMultiplication extends TensorState {
@Param(Array("8", "32"))
protected var inputDepth: Int = _
@Param(Array("8", "32"))
protected var outputDepth: Int = _
@Param(Array("65536", "4096", "32"))
protected var batchSize: Int = _
@transient
private lazy val input = Nd4j.randn(Array(batchSize, inputDepth))
@transient
private lazy val weight = Nd4j.randn(Array(inputDepth, outputDepth))
@Benchmark
final def nd4j(): Array[Float] = {
input.mmul(weight).data().asFloat()
}
trait Benchmarks extends BenchmarkTensors {
@transient
private lazy val unrollThreshold = deviceIds.head.maxComputeUnits * 128
def matrixMultiply(matrix1: Tensor, matrix2: Tensor): Tensor = {
val Array(i, j) = matrix1.shape
if (i >= unrollThreshold) {
// unroll j and k
val columns1 = matrix1.split(1)
Tensor.join(matrix2.split(1).map { column2: Tensor =>
(columns1 zip column2.split(0))
.map {
case (l: Tensor, r: Tensor) =>
l * r.broadcast(l.shape)
}
.reduce[Tensor](_ + _)
})
} else {
// unroll only j
val Array(`j`, k) = matrix2.shape
val product = matrix1.broadcast(Array(i, j, k)) * matrix2.reshape(Array(1, j, k)).broadcast(Array(i, j, k))
product.split(1).reduce[Tensor](_ + _)
}
}
def doBenchmark(): Do[() => Array[Float]] = {
val weight: NonInlineTensor = Tensor.randomNormal(Array(inputDepth, outputDepth))
val input: NonInlineTensor = Tensor.randomNormal(Array(batchSize, inputDepth))
weight.doCache.flatMap { weight =>
input.doCache.map { input =>
{ () =>
matrixMultiply(input, weight).flatArray.blockingAwait
}
}
}
}
}
private var benchmarkResource: Resource[UnitContinuation, Try[() => Array[Float]]] = _
@Setup
final def setup(): Unit = {
// Configuration.OPENCL_LIBRARY_NAME.set("/opt/pocl-1.1/lib/libOpenCL.dylib")
assert(benchmarkResource == null)
val Do(TryT(ResourceT(resourceContinuation))) =
Do.monadicCloseable(Factory[Benchmarks].newInstance()).flatMap(_.doBenchmark())
benchmarkResource = resourceContinuation.blockingAwait()
}
@TearDown(Level.Trial)
final def tearDown(): Unit = {
val benchmarkResource = this.benchmarkResource
this.benchmarkResource = null
benchmarkResource.release.blockingAwait
}
@Benchmark
final def computeDotScala(): Array[Float] = {
benchmarkResource.value.get.apply()
}
}
@Threads(value = Threads.MAX)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Timeout(time = 2, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
class Tanh extends TensorState {
@transient
private lazy val input = Nd4j.randn(Array.fill(numberOfDimensions)(size))
@Benchmark
final def nd4j(): Array[Float] = {
(0 until numberOfIterations)
.foldLeft(input) { (input, _) =>
Transforms.tanh(input)
}
.data()
.asFloat()
}
trait Benchmarks extends BenchmarkTensors {
def doBenchmark(): Do[() => Array[Float]] = {
val input = Tensor.randomNormal(Array.fill(numberOfDimensions)(size))
input.doCache.map { input =>
{ () =>
(0 until numberOfIterations)
.foldLeft[Tensor](input) { (input, _) =>
Tensor.tanh(input)
}
.flatArray
.blockingAwait
}
}
}
}
private var benchmarkResource: Resource[UnitContinuation, Try[() => Array[Float]]] = _
@Setup
final def setup(): Unit = {
assert(benchmarkResource == null)
val Do(TryT(ResourceT(resourceContinuation))) =
Do.monadicCloseable(Factory[Benchmarks].newInstance()).flatMap(_.doBenchmark())
benchmarkResource = resourceContinuation.blockingAwait()
}
@TearDown(Level.Trial)
final def tearDown(): Unit = {
val benchmarkResource = this.benchmarkResource
this.benchmarkResource = null
benchmarkResource.release.blockingAwait
}
@Benchmark
final def computeDotScala(): Array[Float] = {
benchmarkResource.value.get.apply()
}
@Param(Array("100", "10", "1"))
protected var numberOfIterations: Int = _
@Param(Array("2", "3"))
protected var numberOfDimensions: Int = _
@Param(Array("128", "32"))
protected var size: Int = _
}
@Threads(value = Threads.MAX)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Timeout(time = 2, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
class Sum extends TensorState {
@transient
private lazy val input = Nd4j.randn(Array.fill(numberOfDimensions)(size))
@Benchmark
final def nd4j(): Float = {
input.sumNumber().floatValue()
}
trait Benchmarks extends BenchmarkTensors {
def doBenchmark(): Do[() => Float] = {
val input: NonInlineTensor = Tensor.randomNormal(Array.fill(numberOfDimensions)(size))
input.doCache.map { input =>
{ () =>
val Array(v) = input.sum.flatArray.blockingAwait
v
}
}
}
}
private var benchmarkResource: Resource[UnitContinuation, Try[() => Float]] = _
@Setup
final def setup(): Unit = {
assert(benchmarkResource == null)
val Do(TryT(ResourceT(resourceContinuation))) =
Do.monadicCloseable(Factory[Benchmarks].newInstance()).flatMap(_.doBenchmark())
benchmarkResource = resourceContinuation.blockingAwait()
}
@TearDown(Level.Trial)
final def tearDown(): Unit = {
val benchmarkResource = this.benchmarkResource
this.benchmarkResource = null
benchmarkResource.release.blockingAwait
}
@Benchmark
final def computeDotScala(): Float = {
benchmarkResource.value.get.apply()
}
@Param(Array("3", "2"))
protected var numberOfDimensions: Int = _
@Param(Array("512", "128", "32", "16"))
protected var size: Int = _
}
@Threads(value = Threads.MAX)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Timeout(time = 2, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
class RandomNormal extends TensorState {
@Param(Array("3", "2", "1"))
protected var numberOfDimensions: Int = _
@Param(Array("128", "32", "16"))
protected var size: Int = _
@Benchmark
final def nd4j(): Array[Float] = {
Nd4j.randn(Array.fill(numberOfDimensions)(size)).data().asFloat()
}
trait Benchmarks extends BenchmarkTensors {}
var benchmarks: Benchmarks = _
@Setup
final def setup(): Unit = {
assert(benchmarks == null)
benchmarks = Factory[Benchmarks].newInstance()
}
@TearDown(Level.Trial)
final def tearDown(): Unit = {
val benchmarks = this.benchmarks
this.benchmarks = null
benchmarks.monadicClose.blockingAwait
}
@Benchmark
final def computeDotScala(): Array[Float] = {
benchmarks.Tensor.randomNormal(Array.fill(numberOfDimensions)(size)).flatArray.blockingAwait
}
}
@Threads(value = Threads.MAX)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Timeout(time = 2, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
class Convolution extends TensorState {
@transient
private lazy val input = Nd4j.randn(Array(batchSize, depth, imageHeight, imageWidth))
@transient
private lazy val layers = (for (i <- (0 until numberOfLayers).view) yield {
(Nd4j.randn(Array(depth, kernelHeight, kernelWidth, depth)), Nd4j.randn(Array(depth)))
}).toList
private def conv2d(input: INDArray /* batchSize × depth × height × width */,
weight: INDArray /* filterSize × kernelHeight × kernelWidth × depth */,
bias: INDArray): INDArray = {
val Array(numberOfImages, depth, height, width) = input.shape()
val numberOfKernels = weight.shape().head
val col = Convolution.im2col(input, Array(kernelHeight, kernelWidth), Array(1, 1), Array(1, 1))
val permutedCol = col.permute(0, 4, 5, 1, 2, 3)
val depthKernelKernel = depth * kernelHeight * kernelWidth
val operandCol2d = permutedCol.reshape(numberOfImages * height * width, depthKernelKernel)
val reshapedWeight = weight.reshape(numberOfKernels, depthKernelKernel)
val permutedWeight = reshapedWeight.permute(1, 0)
val dotResult = operandCol2d.mmul(permutedWeight)
val plusResult = dotResult.add(bias.broadcast(dotResult.shape(): _*))
val reshapeResult = plusResult.reshape(numberOfImages, height, width, numberOfKernels)
reshapeResult.permute(0, 3, 1, 2)
}
@Benchmark
final def nd4j(): Array[Float] = {
layers
.foldLeft(input) { (input, layer) =>
val (weight, bias) = layer
conv2d(input, weight, bias)
}
.data()
.asFloat()
}
trait Benchmarks extends BenchmarkTensors {
final case class ConvolutionalLayer(weight: NonInlineTensor, bias: NonInlineTensor) {
def forward(input: Tensor): Tensor = {
convolute(input, weight, bias)
}
}
def convolute(input: Tensor /* batchSize × height × width × depth */,
weight: Tensor /* kernelHeight × kernelWidth × depth × filterSize */,
bias: Tensor /* filterSize */ ): Tensor = {
input.shape match {
case Array(batchSize, height, width, depth) =>
weight.shape match {
case Array(kernelHeight, kernelWidth, `depth`, filterSize) =>
bias.shape match {
case Array(`filterSize`) =>
val inputSeq: Seq[Tensor /* batchSize × height × width */ ] = input.split(dimension = 3)
if (inputSeq.size != depth) {
throw new IllegalArgumentException
}
inputSeq.head.shape match {
case Array(batchSize, height, width) =>
case _ =>
throw new IllegalArgumentException
}
val weightSeq: Seq[Seq[Seq[Seq[Tensor]]]] /* filterSize × kernelHeight × kernelWidth × depth */ =
weight.split(dimension = 3).map { khKwD =>
khKwD.shape match {
case Array(kernelHeight, kernelWidth, depth) =>
case _ =>
throw new IllegalArgumentException
}
khKwD.split(dimension = 0).map { kwD =>
kwD.shape match {
case Array(kernelWidth, depth) =>
case _ =>
throw new IllegalArgumentException
}
kwD.split(dimension = 0).map { d =>
d.shape match {
case Array(depth) =>
case _ =>
throw new IllegalArgumentException
}
d.split(dimension = 0)
}
}
}
weightSeq match {
case Seq(h @ Seq(w @ Seq(d, _*), _*), _*)
if h.length == kernelHeight && w.length == kernelWidth && d.length == depth =>
case _ =>
throw new IllegalArgumentException
}
if (weightSeq.length != filterSize) {
throw new IllegalArgumentException
}
val biasSeq: Seq[Tensor] /* filterSize */ = bias.split(dimension = 0)
val outputChannels: Seq[Tensor] = weightSeq.view
.zip(biasSeq)
.map {
case (weightPerFilter, biasPerFilter) =>
val summands: Seq[Tensor] = for {
(offsetY, weightPerRow) <- (-1 to 1).view.zip(weightPerFilter)
(offsetX, weightPerPixel) <- (-1 to 1).view.zip(weightPerRow)
(
inputPerChannel /* batchSize × height × width */,
weightPerChannel /* scalar */
) <- inputSeq.view.zip(weightPerPixel)
} yield {
if (weightPerChannel.shape.nonEmpty) {
throw new IllegalArgumentException
}
inputPerChannel.translate(Array(0, offsetY, offsetX)) *
weightPerChannel.broadcast(Array(batchSize, height, width))
}
biasPerFilter.broadcast(Array(batchSize, height, width)) + summands.reduce(_ + _)
}
Tensor.join(outputChannels)
case _ =>
throw new IllegalArgumentException
}
case _ =>
throw new IllegalArgumentException
}
case _ =>
throw new IllegalArgumentException
}
}
def doBenchmark(): Do[() => Array[Float]] = {
val input: NonInlineTensor = Tensor.randomNormal(Array(batchSize, imageHeight, imageWidth, depth))
val layers = (for (i <- (0 until numberOfLayers).view) yield {
ConvolutionalLayer(weight = Tensor.randomNormal(Array(kernelHeight, kernelWidth, depth, depth)),
bias = Tensor.randomNormal(Array(depth)))
}).toList
input.doCache.flatMap { input =>
layers
.traverseM {
case ConvolutionalLayer(weight, bias) =>
weight.doCache.flatMap { weight =>
bias.doCache.map { bias =>
List(weight, bias)
}
}
}
.map { _ => () =>
layers
.foldLeft[Tensor](input) { (input, layer) =>
layer.forward(input)
}
.flatArray
.blockingAwait
}
}
}
}
private var benchmarkResource: Resource[UnitContinuation, Try[() => Array[Float]]] = _
@Setup
final def setup(): Unit = {
assert(benchmarkResource == null)
val Do(TryT(ResourceT(resourceContinuation))) =
Do.monadicCloseable(Factory[Benchmarks].newInstance()).flatMap(_.doBenchmark())
benchmarkResource = resourceContinuation.blockingAwait()
}
@TearDown(Level.Trial)
final def tearDown(): Unit = {
val benchmarkResource = this.benchmarkResource
this.benchmarkResource = null
benchmarkResource.release.blockingAwait
}
@Benchmark
final def computeDotScala(): Array[Float] = {
benchmarkResource.value.get.apply()
}
// ND4J is too slow when increasing the number of layers.
@Param(Array("1"))
protected var numberOfLayers: Int = _
@Param(Array("3", "1"))
protected var kernelWidth: Int = _
protected def kernelHeight: Int = kernelWidth
@Param(Array("32"))
protected var imageHeight: Int = _
@Param(Array("32"))
protected var imageWidth: Int = _
@Param(Array("128", "32"))
protected var batchSize: Int = _
@Param(Array("8", "3"))
protected var depth: Int = _
}
}