-
Notifications
You must be signed in to change notification settings - Fork 18
/
OpenCL.scala
1433 lines (1221 loc) · 52.5 KB
/
OpenCL.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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.thoughtworks.compute
import scala.collection.JavaConverters._
import java.nio.{ByteBuffer, IntBuffer}
import java.util.concurrent.{ConcurrentHashMap, Executors}
import java.util.concurrent.atomic.AtomicReference
import java.util.regex.Pattern
import com.typesafe.scalalogging.{CanLog, Logger, StrictLogging}
import org.lwjgl.opencl._
import CL10._
import CL12._
import CL11._
import CL20._
import KHRICD._
import org.lwjgl.{BufferUtils, PointerBuffer}
import org.lwjgl.system.MemoryUtil._
import org.lwjgl.system.MemoryStack._
import org.lwjgl.system.Pointer._
import scala.collection.mutable
import com.thoughtworks.each.Monadic._
import com.thoughtworks.compute.Memory.Box
import com.thoughtworks.compute.OpenCL.{Event, checkErrorCode}
import Event.Status
import com.thoughtworks.compute.OpenCL.Exceptions.{DeviceNotFound, InvalidValue}
import org.lwjgl.system.jni.JNINativeInterface
import org.lwjgl.system._
import scala.util.control.Exception.Catcher
import scala.util.control.{NonFatal, TailCalls}
import scala.util.control.TailCalls.TailRec
import scala.util.{Failure, Success, Try}
import scalaz.{-\/, Memo, \/, \/-}
import scalaz.syntax.all._
import com.thoughtworks.continuation._
import com.thoughtworks.feature.Factory
import com.thoughtworks.feature.Factory.inject
import com.thoughtworks.feature.mixins.ImplicitsSingleton
import com.thoughtworks.future._
import com.thoughtworks.raii.AsynchronousPool
import com.thoughtworks.raii.asynchronous._
import com.thoughtworks.raii.covariant._
import com.thoughtworks.tryt.covariant._
import org.slf4j.MDC
import shapeless.Witness
import scala.annotation.tailrec
import scala.concurrent.{ExecutionContext, ExecutionContextExecutor}
import scala.language.higherKinds
/**
* @author 杨博 (Yang Bo)
*/
object OpenCL {
final case class PlatformId[Owner <: Singleton with OpenCL](handle: Long) extends AnyVal {
def name: String = {
val stack = stackPush()
try {
val sizeBuffer = stack.mallocPointer(1)
checkErrorCode(clGetPlatformInfo(handle, CL_PLATFORM_NAME, null: ByteBuffer, sizeBuffer))
val size = sizeBuffer.get(0).toInt
val nameBuffer = stack.malloc(size)
checkErrorCode(clGetPlatformInfo(handle, CL_PLATFORM_NAME, nameBuffer, null))
memUTF8(nameBuffer)
} finally {
stack.close()
}
}
def deviceIdsByType(deviceType: Int): Seq[DeviceId[Owner]] = {
val Array(numberOfDevices) = {
val a = Array(0)
checkErrorCode(clGetDeviceIDs(handle, deviceType, null, a))
a
}
val stack = stackPush()
try {
val deviceIdBuffer = stack.mallocPointer(numberOfDevices)
checkErrorCode(clGetDeviceIDs(handle, deviceType, deviceIdBuffer, null: IntBuffer))
for (i <- 0 until numberOfDevices) yield {
val deviceId = deviceIdBuffer.get(i)
new DeviceId[Owner](deviceId)
}
} finally {
stack.close()
}
}
}
/** Returns a [[String]] for the C string `address`.
*
* @note We don't know the exact charset of the C string. Use [[memASCII]] because lwjgl treats them as ASCII.
*/
private def decodeString(address: Long): String = memASCII(address)
/** Returns a [[String]] for the C string `byteBuffer`.
*
* @note We don't know the exact charset of the C string. Use [[memASCII]] because lwjgl treats them as ASCII.
*/
private def decodeString(byteBuffer: ByteBuffer): String = memASCII(byteBuffer)
@volatile
var defaultLogger: (String, Option[ByteBuffer]) => Unit = { (errorInfo, data) =>
// TODO: Add a test for in the case that Context is closed
Console.err.println(raw"""An OpenCL notify comes out after its corresponding handler is freed
message: $errorInfo
data: $data""")
}
@deprecated(
message = "[[finalize]] method should not be invoked by users.",
since = "[[finalize]] is deprecated in Java 9. However, it is the only way to clean up static native resources."
)
override protected def finalize(): Unit = {
contextCallback.close()
super.finalize()
}
private val contextCallback: CLContextCallback = CLContextCallback.create(new CLContextCallbackI {
def invoke(errInfo: Long, privateInfo: Long, size: Long, userData: Long): Unit = {
val errorInfo = decodeString(errInfo)
val dataOption = if (privateInfo != NULL) {
Some(memByteBuffer(privateInfo, size.toInt))
} else {
None
}
memGlobalRefToObject[OpenCL](userData) match {
case null =>
defaultLogger(decodeString(errInfo), dataOption)
case opencl =>
if (size.isValidInt) {
opencl.handleOpenCLNotification(decodeString(errInfo), dataOption)
} else {
throw new IllegalArgumentException(s"numberOfBytes($size) is too large")
}
}
}
})
object Exceptions {
final class MisalignedSubBufferOffset(message: String = null) extends IllegalArgumentException(message)
final class ExecStatusErrorForEventsInWaitList(message: String = null) extends IllegalArgumentException(message)
final class InvalidProperty(message: String = null) extends IllegalArgumentException(message)
final class PlatformNotFoundKhr(message: String = null) extends NoSuchElementException(message)
final class DeviceNotFound(message: String = null) extends NoSuchElementException(message)
final class DeviceNotAvailable(message: String = null) extends IllegalStateException(message)
final class CompilerNotAvailable(message: String = null) extends IllegalStateException(message)
final class MemObjectAllocationFailure(message: String = null) extends IllegalStateException(message)
final class OutOfResources(message: String = null) extends IllegalStateException(message)
final class OutOfHostMemory(message: String = null) extends IllegalStateException(message)
final class ProfilingInfoNotAvailable(message: String = null) extends IllegalStateException(message)
final class MemCopyOverlap(message: String = null) extends IllegalStateException(message)
final class ImageFormatMismatch(message: String = null) extends IllegalStateException(message)
final class ImageFormatNotSupported(message: String = null) extends IllegalStateException(message)
final class BuildProgramFailure[Owner <: Singleton with OpenCL](
buildLogs: Map[DeviceId[Owner], String] = Map.empty[DeviceId[Owner], String])
extends IllegalStateException({
buildLogs.view
.map {
case (deviceId, buildLog) =>
f"CL_BUILD_PROGRAM_FAILURE on device 0x${deviceId.handle}%X:\n$buildLog"
}
.mkString("\n")
})
final class MapFailure(message: String = null) extends IllegalStateException(message)
final class InvalidValue(message: String = null) extends IllegalArgumentException(message)
final class InvalidDeviceType(message: String = null) extends IllegalArgumentException(message)
final class InvalidPlatform(message: String = null) extends IllegalArgumentException(message)
final class InvalidDevice(message: String = null) extends IllegalArgumentException(message)
final class InvalidContext(message: String = null) extends IllegalArgumentException(message)
final class InvalidQueueProperties(message: String = null) extends IllegalArgumentException(message)
final class InvalidCommandQueue(message: String = null) extends IllegalArgumentException(message)
final class InvalidHostPtr(message: String = null) extends IllegalArgumentException(message)
final class InvalidMemObject(message: String = null) extends IllegalArgumentException(message)
final class InvalidImageFormatDescriptor(message: String = null) extends IllegalArgumentException(message)
final class InvalidImageSize(message: String = null) extends IllegalArgumentException(message)
final class InvalidSampler(message: String = null) extends IllegalArgumentException(message)
final class InvalidBinary(message: String = null) extends IllegalArgumentException(message)
final class InvalidBuildOptions(message: String = null) extends IllegalArgumentException(message)
final class InvalidProgram(message: String = null) extends IllegalArgumentException(message)
final class InvalidProgramExecutable(message: String = null) extends IllegalArgumentException(message)
final class InvalidKernelName(message: String = null) extends IllegalArgumentException(message)
final class InvalidKernelDefinition(message: String = null) extends IllegalArgumentException(message)
final class InvalidKernel(message: String = null) extends IllegalArgumentException(message)
final class InvalidArgIndex(message: String = null) extends IllegalArgumentException(message)
final class InvalidArgValue(message: String = null) extends IllegalArgumentException(message)
final class InvalidArgSize(message: String = null) extends IllegalArgumentException(message)
final class InvalidKernelArgs(message: String = null) extends IllegalArgumentException(message)
final class InvalidWorkDimension(message: String = null) extends IllegalArgumentException(message)
final class InvalidWorkGroupSize(message: String = null) extends IllegalArgumentException(message)
final class InvalidWorkItemSize(message: String = null) extends IllegalArgumentException(message)
final class InvalidGlobalOffset(message: String = null) extends IllegalArgumentException(message)
final class InvalidEventWaitList(message: String = null) extends IllegalArgumentException(message)
final class InvalidEvent(message: String = null) extends IllegalArgumentException(message)
final class InvalidOperation(message: String = null) extends IllegalArgumentException(message)
final class InvalidBufferSize(message: String = null) extends IllegalArgumentException(message)
final class InvalidGlobalWorkSize(message: String = null) extends IllegalArgumentException(message)
final class UnknownErrorCode(errorCode: Int) extends IllegalStateException(s"Unknown error code: $errorCode")
def fromErrorCode(errorCode: Int): Exception = errorCode match {
case CL_PLATFORM_NOT_FOUND_KHR => new Exceptions.PlatformNotFoundKhr
case CL_DEVICE_NOT_FOUND => new Exceptions.DeviceNotFound
case CL_DEVICE_NOT_AVAILABLE => new Exceptions.DeviceNotAvailable
case CL_COMPILER_NOT_AVAILABLE => new Exceptions.CompilerNotAvailable
case CL_MEM_OBJECT_ALLOCATION_FAILURE => new Exceptions.MemObjectAllocationFailure
case CL_OUT_OF_RESOURCES => new Exceptions.OutOfResources
case CL_OUT_OF_HOST_MEMORY => new Exceptions.OutOfHostMemory
case CL_PROFILING_INFO_NOT_AVAILABLE => new Exceptions.ProfilingInfoNotAvailable
case CL_MEM_COPY_OVERLAP => new Exceptions.MemCopyOverlap
case CL_IMAGE_FORMAT_MISMATCH => new Exceptions.ImageFormatMismatch
case CL_IMAGE_FORMAT_NOT_SUPPORTED => new Exceptions.ImageFormatNotSupported
case CL_BUILD_PROGRAM_FAILURE => new Exceptions.BuildProgramFailure
case CL_MAP_FAILURE => new Exceptions.MapFailure
case CL_INVALID_VALUE => new Exceptions.InvalidValue
case CL_INVALID_DEVICE_TYPE => new Exceptions.InvalidDeviceType
case CL_INVALID_PLATFORM => new Exceptions.InvalidPlatform
case CL_INVALID_DEVICE => new Exceptions.InvalidDevice
case CL_INVALID_CONTEXT => new Exceptions.InvalidContext
case CL_INVALID_QUEUE_PROPERTIES => new Exceptions.InvalidQueueProperties
case CL_INVALID_COMMAND_QUEUE => new Exceptions.InvalidCommandQueue
case CL_INVALID_HOST_PTR => new Exceptions.InvalidHostPtr
case CL_INVALID_MEM_OBJECT => new Exceptions.InvalidMemObject
case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR => new Exceptions.InvalidImageFormatDescriptor
case CL_INVALID_IMAGE_SIZE => new Exceptions.InvalidImageSize
case CL_INVALID_SAMPLER => new Exceptions.InvalidSampler
case CL_INVALID_BINARY => new Exceptions.InvalidBinary
case CL_INVALID_BUILD_OPTIONS => new Exceptions.InvalidBuildOptions
case CL_INVALID_PROGRAM => new Exceptions.InvalidProgram
case CL_INVALID_PROGRAM_EXECUTABLE => new Exceptions.InvalidProgramExecutable
case CL_INVALID_KERNEL_NAME => new Exceptions.InvalidKernelName
case CL_INVALID_KERNEL_DEFINITION => new Exceptions.InvalidKernelDefinition
case CL_INVALID_KERNEL => new Exceptions.InvalidKernel
case CL_INVALID_ARG_INDEX => new Exceptions.InvalidArgIndex
case CL_INVALID_ARG_VALUE => new Exceptions.InvalidArgValue
case CL_INVALID_ARG_SIZE => new Exceptions.InvalidArgSize
case CL_INVALID_KERNEL_ARGS => new Exceptions.InvalidKernelArgs
case CL_INVALID_WORK_DIMENSION => new Exceptions.InvalidWorkDimension
case CL_INVALID_WORK_GROUP_SIZE => new Exceptions.InvalidWorkGroupSize
case CL_INVALID_WORK_ITEM_SIZE => new Exceptions.InvalidWorkItemSize
case CL_INVALID_GLOBAL_OFFSET => new Exceptions.InvalidGlobalOffset
case CL_INVALID_EVENT_WAIT_LIST => new Exceptions.InvalidEventWaitList
case CL_INVALID_EVENT => new Exceptions.InvalidEvent
case CL_INVALID_OPERATION => new Exceptions.InvalidOperation
case CL_INVALID_BUFFER_SIZE => new Exceptions.InvalidBufferSize
case CL_INVALID_GLOBAL_WORK_SIZE => new Exceptions.InvalidGlobalWorkSize
case CL_MISALIGNED_SUB_BUFFER_OFFSET => new Exceptions.MisalignedSubBufferOffset
case CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST => new Exceptions.ExecStatusErrorForEventsInWaitList
case CL_INVALID_PROPERTY => new Exceptions.InvalidProperty
case _ => new Exceptions.UnknownErrorCode(errorCode)
}
}
def checkErrorCode(errorCode: Int): Unit = {
errorCode match {
case CL_SUCCESS =>
case _ => throw Exceptions.fromErrorCode(errorCode)
}
}
trait UseFirstDevice extends OpenCL {
@transient
protected lazy val platformId: PlatformId = {
platformIds.head
}
@transient
protected lazy val deviceIds: Seq[DeviceId] = {
val allDeviceIds = platformId.deviceIdsByType(CL_DEVICE_TYPE_ALL)
Seq(allDeviceIds.head)
}
}
trait UseAllDevices extends UseAllDevicesByType {
protected val deviceType: Status = CL_DEVICE_TYPE_ALL
}
trait UseAllCpuDevices extends UseAllDevicesByType {
protected val deviceType: Status = CL_DEVICE_TYPE_CPU
}
trait UseAllGpuDevices extends UseAllDevicesByType {
protected val deviceType: Status = CL_DEVICE_TYPE_GPU
}
trait UseAllDevicesByType extends OpenCL {
protected val deviceType: Int
@transient
protected lazy val (platformId: PlatformId, deviceIds: Seq[DeviceId]) = {
object MatchDeviceType {
def unapply(platformId: PlatformId): Option[Seq[DeviceId]] = {
(try {
platformId.deviceIdsByType(deviceType)
} catch {
case e: DeviceNotFound =>
return None
}) match {
case devices if devices.nonEmpty =>
Some(devices)
case _ =>
None
}
}
}
platformIds.collectFirst {
case platformId @ MatchDeviceType(deviceIds) =>
(platformId, deviceIds)
} match {
case None =>
throw new DeviceNotFound(s"No device of type $deviceType is found")
case Some(pair) =>
pair
}
}
}
private val AmdOrIntelRegex = """AMD|Intel""".r
/**
* @note [[HandleEventInExecutionContextForIntelAndAMDPlatform]] __should__ be unnecessary because
* only OpenCL calls to create contexts or command-queues, or blocking OpenCL operations are undefined behavior,
* according to https://www.khronos.org/registry/OpenCL/sdk/1.2/docs/man/xhtml/clSetEventCallback.html
* and we don't use those forbidden functions.
* Our usage should be fine according to the OpenCL specification.
* However, AMD SDK always crashes for any reentry calls
* (e.g. https://travis-ci.org/Atry/DeepLearning.scala/jobs/318466522),
* no matter if they are blocking or not.
*
* There is also similar bug in Intel's OpenCL implementation
*
* As a workaround, always enable this [[HandleEventInExecutionContextForIntelAndAMDPlatform]] for
* Intel's and AMD's OpenCL implementation.
*/
trait HandleEventInExecutionContextForIntelAndAMDPlatform extends OpenCL {
// FIXME: this plug-in will cause Nvidia OpenCL hang up. Need investigation.
protected val executionContext: ExecutionContext
@transient
private lazy val isEnabled = {
AmdOrIntelRegex.findAllMatchIn(platformId.name).nonEmpty
}
override protected def waitForStatus(event: Event, callbackType: Status): UnitContinuation[Status] =
if (isEnabled) {
super.waitForStatus(event, callbackType).flatMap { status =>
UnitContinuation.execute(status)(executionContext)
}
} else {
super.waitForStatus(event, callbackType)
}
}
trait GlobalExecutionContext {
protected val executionContext: ExecutionContextExecutor = scala.concurrent.ExecutionContext.global
}
trait SingleThreadExecutionContext {
protected val executionContext: ExecutionContextExecutor =
scala.concurrent.ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor())
}
trait CommandQueuePool extends OpenCL {
protected val numberOfCommandQueuesPerDevice: Int
@transient private lazy val commandQueues: Seq[CommandQueue] = {
deviceIds.flatMap { deviceId =>
val capabilities = deviceCapabilities(deviceId)
for (i <- 0 until numberOfCommandQueuesPerDevice) yield {
val supportedProperties = deviceId.longInfo(CL_DEVICE_QUEUE_PROPERTIES)
val properties = Map(
CL_QUEUE_PROPERTIES -> (supportedProperties & CL_QUEUE_ON_DEVICE)
)
createCommandQueue(deviceId, properties)
}
}
}
@transient
protected lazy val Resource(acquireCommandQueue, shutdownCommandQueues) = AsynchronousPool.preloaded(commandQueues)
override def monadicClose: UnitContinuation[Unit] = {
import scalaz.std.iterable._
shutdownCommandQueues >> commandQueues.traverseU_(_.monadicClose) >> super.monadicClose
}
}
final case class DeviceId[Owner <: Singleton with OpenCL](handle: Long) extends AnyVal {
def deviceType: Long = {
val stack = stackPush()
try {
val deviceTypeBuffer = stack.mallocLong(1)
checkErrorCode(clGetDeviceInfo(handle, CL_DEVICE_TYPE, deviceTypeBuffer, null))
deviceTypeBuffer.get(0)
} finally {
stack.close()
}
}
def maxComputeUnits: Int = {
val stack = stackPush()
try {
val outputBuffer = stack.mallocInt(1)
checkErrorCode(clGetDeviceInfo(handle, CL_DEVICE_MAX_COMPUTE_UNITS, outputBuffer, null))
outputBuffer.get(0)
} finally {
stack.close()
}
}
def maxWorkGroupSize: Long = {
val stack = stackPush()
try {
val bufferSizeBuffer = stack.mallocPointer(1)
checkErrorCode(clGetDeviceInfo(handle, CL_DEVICE_MAX_WORK_GROUP_SIZE, bufferSizeBuffer, null))
bufferSizeBuffer.get(0)
} finally {
stack.close()
}
}
def maxWorkItemDimensions: Int = {
val stack = stackPush()
try {
val buffer = stack.mallocInt(1)
checkErrorCode(clGetDeviceInfo(handle, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, buffer, null))
buffer.get(0)
} finally {
stack.close()
}
}
def maxWorkItemSizes: Seq[Long] = {
val stack = stackPush()
try {
val bufferSizeBuffer = stack.mallocPointer(1)
checkErrorCode(clGetDeviceInfo(handle, CL_DEVICE_MAX_WORK_ITEM_SIZES, null: PointerBuffer, bufferSizeBuffer))
bufferSizeBuffer.get(0) match {
case n if n > Int.MaxValue =>
throw new IllegalStateException()
case n =>
val numberOfDimensions = n.toInt
val sizeBuffer = stack.mallocPointer(numberOfDimensions)
checkErrorCode(clGetDeviceInfo(handle, CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeBuffer, null))
val output = Array.ofDim[Long](numberOfDimensions)
sizeBuffer.get(output)
output
}
} finally {
stack.close()
}
}
private[OpenCL] def longInfo(paramName: Int) = {
val stack = stackPush()
try {
val buffer = stack.mallocLong(1)
checkErrorCode(clGetDeviceInfo(handle, paramName, buffer, null))
buffer.get(0)
} finally {
stack.close()
}
}
}
object Event {
private[OpenCL] val eventCallback: CLEventCallback = CLEventCallback.create(new CLEventCallbackI {
final def invoke(event: Long, status: Int, userData: Long): Unit = {
val scalaCallback = try { memGlobalRefToObject[Int => Unit](userData) } finally {
JNINativeInterface.DeleteGlobalRef(userData)
}
scalaCallback(status)
}
})
type Status = Int
}
final case class CommandQueue[Owner <: Singleton with OpenCL](handle: Long)
extends AnyVal
with MonadicCloseable[UnitContinuation] {
def deviceId: DeviceId[Owner] = {
val stack = stackPush()
try {
val deviceIdBuffer = stack.mallocPointer(1)
checkErrorCode(clGetCommandQueueInfo(handle, CL_QUEUE_DEVICE, deviceIdBuffer, null))
DeviceId(deviceIdBuffer.get(0))
} finally {
stack.close()
}
}
def flush(): Unit = {
checkErrorCode(clFlush(handle))
}
def monadicClose: UnitContinuation[Unit] = UnitContinuation.delay {
checkErrorCode(clReleaseCommandQueue(handle))
}
}
final case class Event[Owner <: Singleton with OpenCL](handle: Long)
extends AnyVal
with MonadicCloseable[UnitContinuation] {
def release(): Unit = {
checkErrorCode(clReleaseEvent(handle))
}
def retain(): Unit = {
checkErrorCode(clRetainEvent(handle))
}
def referenceCount: Int = {
val stack = stackPush()
try {
val intBuffer = stack.mallocInt(1)
checkErrorCode(clGetEventInfo(handle, CL_EVENT_REFERENCE_COUNT, intBuffer, null))
intBuffer.get(0)
} finally {
stack.close()
}
}
def waitFor(callbackType: Status)(implicit
witnessOwner: Witness.Aux[Owner]): Future[Unit] = {
// The cast is a workaround for https://github.com/milessabin/shapeless/issues/753
val self = this.asInstanceOf[witnessOwner.value.Event]
val continuation = witnessOwner.value.waitForStatus(self, callbackType).flatMap[Try[Unit]] {
case `callbackType` =>
UnitContinuation.now(Success(()))
case errorCode if errorCode < 0 =>
UnitContinuation.now(Failure(Exceptions.fromErrorCode(errorCode)))
case status =>
throw new IllegalStateException(raw"""Invalid event status $status""")
}
Future(TryT(continuation))
}
def waitForComplete()(
implicit
witnessOwner: Witness.Aux[Owner]): Future[Unit] = waitFor(CL_COMPLETE)
def monadicClose: UnitContinuation[Unit] = {
UnitContinuation.delay {
release()
}
}
}
object DeviceBuffer {
implicit def bufferBox[Owner <: Singleton with OpenCL, Element]: Box.Aux[DeviceBuffer[Owner, Element], Pointer] =
new Box[DeviceBuffer[Owner, Element]] {
override type Raw = Pointer
override def box(raw: Raw): DeviceBuffer[Owner, Element] =
new DeviceBuffer[Owner, Element](raw.address())
override def unbox(boxed: DeviceBuffer[Owner, Element]): Raw = new Pointer.Default(boxed.handle) {}
}
}
/** A [[https://www.khronos.org/registry/OpenCL/sdk/2.1/docs/man/xhtml/abstractDataTypes.html cl_mem]]
* whose [[org.lwjgl.opencl.CL10.CL_MEM_TYPE CL_MEM_TYPE]] is buffer [[org.lwjgl.opencl.CL10.CL_MEM_OBJECT_BUFFER CL_MEM_OBJECT_BUFFER]].
* @param handle The underlying `cl_mem`.
* @note comment out `extends AnyVal` in case of https://github.com/scala/bug/issues/10647
*/
final case class DeviceBuffer[Owner <: OpenCL with Singleton, Element](handle: Long) /* extends AnyVal */
extends MonadicCloseable[UnitContinuation] {
deviceBuffer =>
def retain() = {
checkErrorCode(clRetainMemObject(handle))
}
def release(): Unit = {
checkErrorCode(clReleaseMemObject(handle))
}
def monadicClose: UnitContinuation[Unit] = {
UnitContinuation.delay {
release()
}
}
def slice(offset: Int, size: Int)(implicit
memory: Memory[Element]): Do[DeviceBuffer[Owner, Element]] = {
Do.monadicCloseable {
val stack = stackPush()
try {
val errorCode = stack.ints(0)
val region = CLBufferRegion.mallocStack(stack)
region.set(offset.toLong * memory.numberOfBytesPerElement, size.toLong * memory.numberOfBytesPerElement)
val newHandle = nclCreateSubBuffer(handle,
CL_MEM_READ_WRITE,
CL_BUFFER_CREATE_TYPE_REGION,
region.address(),
memAddress(errorCode))
checkErrorCode(errorCode.get(0))
DeviceBuffer[Owner, Element](newHandle)
} finally {
stack.close()
}
}
}
def numberOfBytes: Int = {
val sizeBuffer: Array[Long] = Array(0L)
checkErrorCode(clGetMemObjectInfo(handle, CL_MEM_SIZE, sizeBuffer, null))
val Array(value) = sizeBuffer
if (value.isValidInt) {
value.toInt
} else {
throw new IllegalStateException(s"Buffer's numberOfBytes($value) is too large")
}
}
def length(implicit memory: Memory[Element]): Int = numberOfBytes / memory.numberOfBytesPerElement
/** Returns an asynchronous operation of a buffer on host.
*
* The buffer may be [[java.nio.FloatBuffer FloatBuffer]],
* [[java.nio.DoubleBuffer DoubleBuffer]]
* or other buffer types according to `Element`.
*
* @note The buffer is allocated by lwjgl, not JRE.
* As a result, you can only use the buffer inside a `map` or `flatMap` block,
* then it will be released by [[com.thoughtworks.raii.asynchronous.Do Do]] automatically.
* Assigning the buffer to another variable used outside `map` or `flatMap` block
* will cause memory access error.
*
*/
final def toHostBuffer(preconditionEvents: Event[Owner]*)(implicit witnessOwner: Witness.Aux[Owner],
memory: Memory[Element]): Do[memory.HostBuffer] = {
Do(TryT(ResourceT(UnitContinuation.delay {
val hostBuffer = memory.allocate(length)
Resource(value = Success(hostBuffer), release = UnitContinuation.delay { memory.free(hostBuffer) })
}))).flatMap { hostBuffer =>
witnessOwner.value
.dispatchReadBuffer[Element, memory.HostBuffer](
this.asInstanceOf[witnessOwner.value.DeviceBuffer[Element]],
hostBuffer,
preconditionEvents.asInstanceOf[Seq[witnessOwner.value.Event]]: _*)(memory)
.intransitiveFlatMap { event =>
Do.garbageCollected(event.waitForComplete()).map { _: Unit =>
hostBuffer
}
}
}
}
}
final case class Kernel[Owner <: OpenCL with Singleton](handle: Long)
extends AnyVal
with MonadicCloseable[UnitContinuation] {
def preferredWorkGroupSizeMultiple(deviceId: DeviceId[Owner]) = {
val stack = stackPush()
try {
val pointerBuffer = stack.mallocPointer(1)
checkErrorCode(
clGetKernelWorkGroupInfo(handle,
deviceId.handle,
CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE,
pointerBuffer,
null))
pointerBuffer.get(0)
} finally {
stack.close()
}
}
def workGroupSize(deviceId: DeviceId[Owner]) = {
val stack = stackPush()
try {
val pointerBuffer = stack.mallocPointer(1)
checkErrorCode(
clGetKernelWorkGroupInfo(handle, deviceId.handle, CL_KERNEL_WORK_GROUP_SIZE, pointerBuffer, null))
pointerBuffer.get(0)
} finally {
stack.close()
}
}
def setLocalMemorySize[A](argIndex: Int, size: Long)(implicit memory: Memory[A]): Unit = {
checkErrorCode(nclSetKernelArg(handle, argIndex, size * memory.numberOfBytesPerElement, NULL))
}
def update[A](argIndex: Int, a: A)(implicit memory: Memory[A]): Unit = {
val sizeofParameter = memory.numberOfBytesPerElement
val stack = stackPush()
try {
val byteBuffer = stack.malloc(sizeofParameter)
memory.put(memory.fromByteBuffer(byteBuffer), 0, a)
checkErrorCode(nclSetKernelArg(handle, argIndex, sizeofParameter, memAddress(byteBuffer)))
} finally {
stack.close()
}
}
def functionName: String = {
val stack = stackPush()
try {
val functionNameSizePointer = stack.mallocPointer(1)
checkErrorCode(
clGetKernelInfo(this.handle, CL_KERNEL_FUNCTION_NAME, null: PointerBuffer, functionNameSizePointer))
val functionNameSize = functionNameSizePointer.get(0).toInt
val functionNameBuffer = stack.malloc(functionNameSize)
checkErrorCode(
clGetKernelInfo(this.handle, CL_KERNEL_FUNCTION_NAME, functionNameBuffer, functionNameSizePointer))
decodeString(functionNameBuffer)
} finally {
stack.close()
}
}
@inline
def enqueue(commandQueue: CommandQueue[Owner],
globalWorkOffset: Option[Seq[Long]] = None,
globalWorkSize: Seq[Long],
localWorkSize: Option[Seq[Long]] = None,
waitingEvents: Seq[Long] = Array.empty[Long]): Do[Event[Owner]] = {
def replaceScalar(dimensions: Seq[Long]) = {
if (dimensions.isEmpty) {
Seq(1L)
} else {
dimensions
}
}
val checkedGlobalWorkSize = replaceScalar(globalWorkSize)
val checkedGlobalWorkOffset = globalWorkOffset.map(replaceScalar)
val checkedLocalWorkSize = localWorkSize.map(replaceScalar)
def optionalStackPointerBuffer(option: Option[Seq[Long]]): MemoryStack => PointerBuffer = {
option match {
case None =>
Function.const(null)
case Some(pointers) =>
_.pointers(pointers: _*)
}
}
val globalWorkOffsetBuffer = optionalStackPointerBuffer(checkedGlobalWorkOffset)
val localWorkSizeBuffer = optionalStackPointerBuffer(checkedLocalWorkSize)
Do.monadicCloseable {
val stack = stackPush()
val outputEvent = try {
val outputEventBuffer = stack.pointers(0L)
val inputEventBuffer = if (waitingEvents.isEmpty) {
null
} else {
stack.pointers(waitingEvents: _*)
}
checkErrorCode(
clEnqueueNDRangeKernel(
commandQueue.handle,
handle,
checkedGlobalWorkSize.length,
globalWorkOffsetBuffer(stack),
stack.pointers(checkedGlobalWorkSize: _*),
localWorkSizeBuffer(stack),
inputEventBuffer,
outputEventBuffer
)
)
Event[Owner](outputEventBuffer.get(0))
} finally {
stack.close()
}
commandQueue.flush()
outputEvent
}
}
def monadicClose: UnitContinuation[Unit] = {
UnitContinuation.delay {
checkErrorCode(clReleaseKernel(handle))
}
}
}
private[compute] final case class Program[Owner <: OpenCL with Singleton](handle: Long)
extends AnyVal
with MonadicCloseable[UnitContinuation] {
def deviceIds: Seq[DeviceId[Owner]] = {
val stack = stackPush()
try {
val sizeBuffer = stack.mallocPointer(1)
checkErrorCode(clGetProgramInfo(this.handle, CL_PROGRAM_DEVICES, null: PointerBuffer, sizeBuffer))
val numberOfDeviceIds = sizeBuffer.get(0).toInt / POINTER_SIZE
val programDevicesBuffer = stack.mallocPointer(numberOfDeviceIds)
checkErrorCode(clGetProgramInfo(this.handle, CL_PROGRAM_DEVICES, programDevicesBuffer, null: PointerBuffer))
(0 until numberOfDeviceIds).map { i =>
DeviceId[Owner](programDevicesBuffer.get(i))
}
} finally {
stack.close()
}
}
def createKernels()(implicit witness: Witness.Aux[Owner]): Seq[Kernel[Owner]] = {
witness.value.createKernels(this.asInstanceOf[witness.value.Program]).asInstanceOf[Seq[Kernel[Owner]]]
}
/** Creates single kernel from this [[Program]].
*
* @throws InvalidValue if the this [[Program]] has more than one kernel.
*/
def createKernel()(implicit witness: Witness.Aux[Owner]): Kernel[Owner] = {
witness.value.createKernel(this.asInstanceOf[witness.value.Program]).asInstanceOf[Kernel[Owner]]
}
private def buildLogs(deviceIds: Seq[DeviceId[Owner]]): Map[DeviceId[Owner], String] = {
val stack = stackPush()
try {
val sizeBuffer = stack.mallocPointer(1)
deviceIds.view.map { deviceId =>
checkErrorCode(
clGetProgramBuildInfo(this.handle, deviceId.handle, CL_PROGRAM_BUILD_LOG, null: PointerBuffer, sizeBuffer))
val logBuffer = MemoryUtil.memAlloc(sizeBuffer.get(0).toInt) //stack.malloc()
try {
checkErrorCode(clGetProgramBuildInfo(this.handle, deviceId.handle, CL_PROGRAM_BUILD_LOG, logBuffer, null))
(deviceId, decodeString(logBuffer))
} finally {
MemoryUtil.memFree(logBuffer)
}
}.toMap
} finally {
stack.close()
}
}
private def checkBuildErrorCode(deviceIdsOption: Option[Seq[DeviceId[Owner]]], errorCode: Int): Unit = {
errorCode match {
case CL_BUILD_PROGRAM_FAILURE =>
val logs = deviceIdsOption match {
case None => buildLogs(this.deviceIds)
case Some(ids) => buildLogs(ids)
}
throw new Exceptions.BuildProgramFailure(logs)
case _ => checkErrorCode(errorCode)
}
}
def build(deviceIds: Seq[DeviceId[Owner]], options: CharSequence = ""): Unit = {
val stack = stackPush()
try {
checkBuildErrorCode(
Some(deviceIds),
clBuildProgram(handle, stack.pointers(deviceIds.view.map(_.handle): _*), options, null, NULL))
} finally {
stack.close()
}
}
def build(options: CharSequence): Unit = {
checkBuildErrorCode(None, clBuildProgram(handle, null, options, null, NULL))
}
def build()(implicit witness: Witness.Aux[Owner]): Unit = build(witness.value.defaultProgramOptions)
def monadicClose = UnitContinuation.delay {
OpenCL.checkErrorCode(clReleaseProgram(handle))
}
def kernelNames(): Seq[String] = {
val stack = stackPush()
try {
val sizeBuffer = stack.mallocPointer(1)
checkErrorCode(clGetProgramInfo(this.handle, CL_PROGRAM_KERNEL_NAMES, null: ByteBuffer, sizeBuffer))
val nameBuffer = stack.malloc(sizeBuffer.get(0).toInt)
checkErrorCode(clGetProgramInfo(this.handle, CL_PROGRAM_KERNEL_NAMES, nameBuffer, null: PointerBuffer))
memUTF8(nameBuffer).split(';')
} finally {
stack.close()
}
}
}
object Program {
@deprecated(
message = "[[finalize]] method should not be invoked by users.",
since = "[[finalize]] is deprecated in Java 9. However, it is the only way to clean up static native resources."
)
override protected def finalize(): Unit = {
programCallback.close()
super.finalize()
}
val programCallback = CLProgramCallback.create(new CLProgramCallbackI {
def invoke(program: Long, userData: Long): Unit = {
val scalaCallback = try {
memGlobalRefToObject[Unit => Unit](userData)
} finally {
JNINativeInterface.DeleteGlobalRef(userData)
}
scalaCallback(())
}
})
}
private[OpenCL] object DontReleaseEventTooEarly {
private[DontReleaseEventTooEarly] sealed trait EarlyEventState
private[DontReleaseEventTooEarly] case object EarlyEventClosed extends EarlyEventState
private[DontReleaseEventTooEarly] sealed trait EarlyEventList extends EarlyEventState
private[DontReleaseEventTooEarly] case object EarlyEventNil extends EarlyEventList
private[DontReleaseEventTooEarly] type AnyEvent = Event[_ <: Singleton with OpenCL]
private[DontReleaseEventTooEarly] final case class EarlyEventCons(head: AnyEvent, tail: EarlyEventList)
extends EarlyEventList
}
/** A plug-in that retains every [[Event]] created by `clEnqueueReadBuffer`
* and waiting at least one second before releasing it.
*
* @note This is a workaround for https://github.com/ThoughtWorksInc/Compute.scala/issues/51
*/
trait DontReleaseEventTooEarly extends OpenCL {
import DontReleaseEventTooEarly._
override protected def enqueueReadBuffer[Element, Destination](
commandQueue: CommandQueue,
deviceBuffer: DeviceBuffer[Element],
hostBuffer: Destination,
preconditionEvents: Event*)(implicit memory: Memory.Aux[Element, Destination]): Do[Event] =