forked from microo8/blackcl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.float32.go
94 lines (84 loc) · 2.23 KB
/
vector.float32.go
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
package blackcl
/*
#cgo CFLAGS: -I CL
#cgo !darwin LDFLAGS: -lOpenCL
#cgo darwin LDFLAGS: -framework OpenCL
#define CL_SILENCE_DEPRECATION
#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL/cl.h>
#endif
*/
import "C"
import (
"errors"
"unsafe"
)
//VectorFloat32 is a memory buffer on device that holds []float32
type VectorFloat32 struct {
buf *buffer
}
//Length the length of the vector
func (v *VectorFloat32) Length() int {
return v.buf.size / float32CLSize
}
//Release releases the buffer on the device
func (v *VectorFloat32) Release() error {
return v.buf.Release()
}
//NewVector allocates new vector buffer with specified length
func (d *Device) NewVectorFloat32(length int) (*VectorFloat32, error) {
size := length * float32CLSize
buf, err := newBuffer(d, size)
if err != nil {
return nil, err
}
return &VectorFloat32{buf: &buffer{memobj: buf, device: d, size: size}}, nil
}
//NewVector allocates new vector buffer with specified length
func (d *Device) NewVectorFloat32With(data []float32) (*VectorFloat32, error) {
size := len(data) * float32CLSize
buf, err := newBuffer(d, size)
if err != nil {
return nil, err
}
v := &VectorFloat32{buf: &buffer{memobj: buf, device: d, size: size}}
if err = <-v.Copy(data); err != nil {
return nil, err
}
return v, nil
}
//Copy copies the float32 data from host data to device buffer
//it's a non-blocking call, channel will return an error or nil if the data transfer is complete
func (v *VectorFloat32) Copy(data []float32) <-chan error {
if v.Length() != len(data) {
ch := make(chan error, 1)
ch <- errors.New("vector length not equal to data length")
return ch
}
return v.buf.copy(len(data)*float32CLSize, unsafe.Pointer(&data[0]))
}
//Data gets float32 data from device, it's a blocking call
func (v *VectorFloat32) Data() ([]float32, error) {
data := make([]float32, v.buf.size/float32CLSize)
err := toErr(C.clEnqueueReadBuffer(
v.buf.device.queue,
v.buf.memobj,
C.CL_TRUE,
0,
C.size_t(v.buf.size),
unsafe.Pointer(&data[0]),
0,
nil,
nil,
))
if err != nil {
return nil, err
}
return data, nil
}
//Map applies an map kernel on all elements of the vector
func (v *VectorFloat32) Map(k *Kernel) <-chan error {
return k.Global(v.Length()).Local(1).Run(v)
}