cclient.go 6.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
package main

/*
#include <string.h>
typedef enum {
  PADDLE_ELEMENT_TYPE_INT32   = 0,
  PADDLE_ELEMENT_TYPE_UINT32  = 1,
  PADDLE_ELEMENT_TYPE_INT64   = 2,
  PADDLE_ELEMENT_TYPE_UINT64  = 3,
  PADDLE_ELEMENT_TYPE_FLOAT32 = 4,
  PADDLE_ELEMENT_TYPE_FLOAT64 = 5,
} paddle_element_type;

typedef struct {
  char*               name;
  paddle_element_type element_type;
17
  unsigned char*      content;
18 19 20
  int                 content_len;
} paddle_parameter, paddle_gradient;

21
typedef int paddle_pserver_client;
H
Helin Wang 已提交
22 23
#define PSERVER_ERROR -1
#define PSERVER_OK 0
24 25 26 27
*/
import "C"

import (
28
	"strings"
29 30 31
	"sync"
	"unsafe"

32
	"github.com/PaddlePaddle/Paddle/go/pserver"
Q
Qiao Longfei 已提交
33
	"github.com/PaddlePaddle/Paddle/go/pserver/client"
H
Helin Wang 已提交
34
	log "github.com/sirupsen/logrus"
35 36
)

H
Helin Wang 已提交
37
var nullPtr = unsafe.Pointer(uintptr(0))
38
var mu sync.Mutex
Q
Qiao Longfei 已提交
39
var handleMap = make(map[C.paddle_pserver_client]*client.Client)
40
var curHandle C.paddle_pserver_client
41

Q
Qiao Longfei 已提交
42
func add(c *client.Client) C.paddle_pserver_client {
43 44 45 46 47 48 49 50
	mu.Lock()
	defer mu.Unlock()
	client := curHandle
	curHandle++
	handleMap[client] = c
	return client
}

Q
Qiao Longfei 已提交
51
func get(client C.paddle_pserver_client) *client.Client {
52 53 54 55 56
	mu.Lock()
	defer mu.Unlock()
	return handleMap[client]
}

Q
Qiao Longfei 已提交
57
func remove(client C.paddle_pserver_client) *client.Client {
58 59 60 61 62 63 64 65
	mu.Lock()
	defer mu.Unlock()
	h := handleMap[client]
	delete(handleMap, client)
	return h
}

func cArrayToSlice(p unsafe.Pointer, len int) []byte {
H
Helin Wang 已提交
66 67 68 69
	if p == nullPtr {
		return nil
	}

70 71 72 73
	// create a Go clice backed by a C array, reference:
	// https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
	//
	// Go garbage collector will not interact with this data, need
H
Helin Wang 已提交
74
	// to be freed properly.
75 76 77
	return (*[1 << 30]byte)(p)[:len:len]
}

78 79 80 81 82 83
type selector bool

func (s selector) Select() bool {
	return bool(s)
}

Q
Qiao Longfei 已提交
84
type lister []client.Server
85

Q
Qiao Longfei 已提交
86
func (l lister) List() []client.Server {
87 88 89
	return l
}

90
//export paddle_new_pserver_client
91
func paddle_new_pserver_client(addrs *C.char, selected int) C.paddle_pserver_client {
92 93
	a := C.GoString(addrs)
	as := strings.Split(a, ",")
Q
Qiao Longfei 已提交
94
	servers := make([]client.Server, len(as))
95 96 97 98
	for i := range as {
		servers[i].Index = i
		servers[i].Addr = as[i]
	}
Q
Qiao Longfei 已提交
99
	c := client.NewClient(lister(servers), len(as), selector(selected != 0))
100 101 102
	return add(c)
}

103
//export paddle_new_etcd_pserver_client
H
Helin Wang 已提交
104
func paddle_new_etcd_pserver_client(etcdEndpoints *C.char, selected int) C.paddle_pserver_client {
Q
Qiao Longfei 已提交
105
	// TODO(Longfei: use etcd lock to decide which trainer to initialize the parameters)
H
Helin Wang 已提交
106 107 108
	addr := C.GoString(etcdEndpoints)
	etcdClient := client.NewEtcd(addr)
	c := client.NewClient(etcdClient, etcdClient.Desired(), selector(selected != 0))
Q
Qiao Longfei 已提交
109
	return add(c)
110 111
}

112
//export paddle_pserver_client_release
113
func paddle_pserver_client_release(client C.paddle_pserver_client) {
114
	remove(client)
115 116 117
}

//export paddle_begin_init_params
118
func paddle_begin_init_params(client C.paddle_pserver_client) C.int {
119
	c := get(client)
120
	if selected := c.BeginInitParams(); selected {
121 122
		return 1
	}
H
Helin Wang 已提交
123
	return C.PSERVER_OK
124 125 126
}

//export paddle_init_param
H
Helin Wang 已提交
127
func paddle_init_param(client C.paddle_pserver_client, param C.paddle_parameter, paramConfig unsafe.Pointer, configLen C.int) C.int {
128 129 130 131 132
	et := pserver.ElementType(param.element_type)
	name := C.GoString(param.name)
	content := cArrayToSlice(unsafe.Pointer(param.content), int(param.content_len))
	pc := pserver.ParameterWithConfig{
		Param:  pserver.Parameter{Name: name, ElementType: et, Content: content},
H
Helin Wang 已提交
133
		Config: cArrayToSlice(paramConfig, int(configLen)),
134 135 136
	}
	c := get(client)
	err := c.InitParam(pc)
137

138
	if err != nil {
139
		if err.Error() == pserver.AlreadyInitialized {
140
			log.Warningf("parameter %s already initialized, treat paddle_init_param as sucessful.", name)
H
Helin Wang 已提交
141
			return C.PSERVER_OK
142
		}
H
Helin Wang 已提交
143
		log.Errorln(err)
H
Helin Wang 已提交
144
		return C.PSERVER_ERROR
145 146
	}

H
Helin Wang 已提交
147
	return C.PSERVER_OK
148 149 150
}

//export paddle_finish_init_params
151
func paddle_finish_init_params(client C.paddle_pserver_client) C.int {
152 153 154
	c := get(client)
	err := c.FinishInitParams()
	if err != nil {
155
		if err.Error() == pserver.AlreadyInitialized {
H
Helin Wang 已提交
156
			log.Warningln("parameters already initialized, treat paddle_finish_init_params as sucessful.")
H
Helin Wang 已提交
157
			return C.PSERVER_OK
158 159
		}

H
Helin Wang 已提交
160
		log.Errorln(err)
H
Helin Wang 已提交
161
		return C.PSERVER_ERROR
162 163
	}

H
Helin Wang 已提交
164
	return C.PSERVER_OK
165 166 167
}

//export paddle_send_grads
168
func paddle_send_grads(client C.paddle_pserver_client, grads **C.paddle_gradient, total C.int) C.int {
169 170
	var gs []pserver.Gradient
	for i := 0; i < int(total); i++ {
171
		grad := *(**C.paddle_gradient)(unsafe.Pointer((uintptr(unsafe.Pointer(grads)) + uintptr(i)*unsafe.Sizeof(*grads))))
172 173 174 175 176 177 178 179 180
		et := pserver.ElementType(grad.element_type)
		name := C.GoString(grad.name)
		content := cArrayToSlice(unsafe.Pointer(grad.content), int(grad.content_len))
		gs = append(gs, pserver.Gradient{Name: name, ElementType: et, Content: content})
	}

	c := get(client)
	err := c.SendGrads(gs)
	if err != nil {
H
Helin Wang 已提交
181
		log.Errorln(err)
H
Helin Wang 已提交
182
		return C.PSERVER_ERROR
183 184
	}

H
Helin Wang 已提交
185
	return C.PSERVER_OK
186 187 188
}

//export paddle_get_params
189
func paddle_get_params(client C.paddle_pserver_client, dst **C.paddle_parameter, total C.int) C.int {
190 191
	var ns []string
	for i := 0; i < int(total); i++ {
192 193
		param := *(**C.paddle_parameter)(unsafe.Pointer((uintptr(unsafe.Pointer(dst)) + uintptr(i)*unsafe.Sizeof(*dst))))
		ns = append(ns, C.GoString(param.name))
194 195 196 197
	}
	c := get(client)
	ps, err := c.GetParams(ns)
	if err != nil {
H
Helin Wang 已提交
198
		log.Errorln(err)
H
Helin Wang 已提交
199
		return C.PSERVER_ERROR
200 201
	}

202
	if len(ps) != len(ns) {
H
Helin Wang 已提交
203 204 205 206
		pn := make([]string, len(ps))
		for i, p := range ps {
			pn[i] = p.Name
		}
207
		log.Errorf("pserver returned wrong number of parameters. Requested: %s, returned: %s.", strings.Join(pn, ", "), strings.Join(ns, ", "))
H
Helin Wang 已提交
208
		return C.PSERVER_ERROR
209 210 211 212
	}

	for i := range ps {
		if ns[i] != ps[i].Name {
H
Helin Wang 已提交
213 214 215 216
			pn := make([]string, len(ps))
			for i, p := range ps {
				pn[i] = p.Name
			}
217
			log.Errorf("pserver returned wrong parameters, or not in requested order. Requested: %s, returned: %s.", strings.Join(pn, ", "), strings.Join(ns, ", "))
H
Helin Wang 已提交
218
			return C.PSERVER_ERROR
219
		}
220
	}
221

222
	for i := 0; i < int(total); i++ {
223
		p := ps[i]
H
Helin Wang 已提交
224 225 226
		param := *(**C.paddle_parameter)(unsafe.Pointer((uintptr(unsafe.Pointer(dst)) + uintptr(i)*unsafe.Sizeof(*dst))))

		if unsafe.Pointer(param) == nullPtr {
H
Helin Wang 已提交
227
			log.Errorln("must pre-allocate parameter.")
H
Helin Wang 已提交
228
			return C.PSERVER_ERROR
229 230 231 232
		}

		if unsafe.Pointer(param.content) != nullPtr {
			if int(param.content_len) != len(p.Content) {
H
Helin Wang 已提交
233
				log.Errorf("the pre-allocated content len does not match parameter content len. Pre-allocated len: %d, returned len: %d", param.content_len, len(p.Content))
234
				return C.PSERVER_ERROR
235 236 237
			}
		}

H
Helin Wang 已提交
238
		C.memcpy(unsafe.Pointer(param.content), unsafe.Pointer(&p.Content[0]), C.size_t(len(p.Content)))
239 240 241 242
		param.content_len = C.int(len(p.Content))
		param.element_type = C.paddle_element_type(p.ElementType)
	}

H
Helin Wang 已提交
243
	return C.PSERVER_OK
244 245 246
}

//export paddle_save_model
247
func paddle_save_model(client C.paddle_pserver_client, path *C.char) C.int {
248 249
	p := C.GoString(path)
	c := get(client)
250
	err := c.Save(p)
251
	if err != nil {
H
Helin Wang 已提交
252
		log.Errorln(err)
H
Helin Wang 已提交
253
		return C.PSERVER_ERROR
254 255
	}

H
Helin Wang 已提交
256
	return C.PSERVER_OK
257 258 259
}

func main() {} // Required but ignored