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

/*
#include <stdlib.h>
#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;
18
  unsigned char*      content;
19 20 21
  int                 content_len;
} paddle_parameter, paddle_gradient;

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

import (
	"log"
30
	"strings"
31 32 33
	"sync"
	"unsafe"

34
	"github.com/PaddlePaddle/Paddle/go/pserver"
35 36
)

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

42
func add(c *pserver.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
}

51
func get(client C.paddle_pserver_client) *pserver.Client {
52 53 54 55 56
	mu.Lock()
	defer mu.Unlock()
	return handleMap[client]
}

57
func remove(client C.paddle_pserver_client) *pserver.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 84 85 86 87 88 89
type selector bool

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

type lister []pserver.Server

func (l lister) List() []pserver.Server {
	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 94 95 96 97 98
	a := C.GoString(addrs)
	as := strings.Split(a, ",")
	servers := make([]pserver.Server, len(as))
	for i := range as {
		servers[i].Index = i
		servers[i].Addr = as[i]
	}
H
Helin Wang 已提交
99
	c := pserver.NewClient(lister(servers), len(as), selector(selected != 0))
100 101 102
	return add(c)
}

103
//export paddle_new_etcd_pserver_client
104
func paddle_new_etcd_pserver_client(etcd_addr *C.char) C.paddle_pserver_client {
105 106 107 108
	// TODO(helin): fault tolerant pserver client using etcd.
	panic("not implemented.")
}

109
//export paddle_pserver_client_release
110
func paddle_pserver_client_release(client C.paddle_pserver_client) {
111
	remove(client)
112 113 114
}

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

//export paddle_init_param
124
func paddle_init_param(client C.paddle_pserver_client, param C.paddle_parameter, param_config unsafe.Pointer, config_len C.int) C.int {
125 126 127 128 129 130 131 132 133
	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},
		Config: cArrayToSlice(param_config, int(config_len)),
	}
	c := get(client)
	err := c.InitParam(pc)
134

135
	if err != nil {
136
		if err.Error() == pserver.AlreadyInitialized {
H
Helin Wang 已提交
137
			log.Printf("parameter %s already initialized, treat paddle_init_param as sucessful.\n", name)
H
Helin Wang 已提交
138
			return C.PSERVER_OK
139
		}
140
		log.Println(err)
H
Helin Wang 已提交
141
		return C.PSERVER_ERROR
142 143
	}

H
Helin Wang 已提交
144
	return C.PSERVER_OK
145 146 147
}

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

157
		log.Println(err)
H
Helin Wang 已提交
158
		return C.PSERVER_ERROR
159 160
	}

H
Helin Wang 已提交
161
	return C.PSERVER_OK
162 163 164
}

//export paddle_send_grads
165
func paddle_send_grads(client C.paddle_pserver_client, grads **C.paddle_gradient, total C.int) C.int {
166 167
	var gs []pserver.Gradient
	for i := 0; i < int(total); i++ {
168
		grad := *(**C.paddle_gradient)(unsafe.Pointer((uintptr(unsafe.Pointer(grads)) + uintptr(i)*unsafe.Sizeof(*grads))))
169 170 171 172 173 174 175 176 177 178
		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 {
		log.Println(err)
H
Helin Wang 已提交
179
		return C.PSERVER_ERROR
180 181
	}

H
Helin Wang 已提交
182
	return C.PSERVER_OK
183 184 185
}

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

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

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

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

		if unsafe.Pointer(param) == nullPtr {
H
Helin Wang 已提交
224
			log.Println("must pre-allocate parameter.")
H
Helin Wang 已提交
225
			return C.PSERVER_ERROR
H
Helin Wang 已提交
226
		} else {
H
Helin Wang 已提交
227
			if unsafe.Pointer(param.content) != nullPtr {
228
				if int(param.content_len) != len(p.Content) {
H
Helin Wang 已提交
229
					log.Printf("the pre-allocated content len does not match parameter content len. Pre-allocated len: %d, returned len: %d", param.content_len, len(p.Content))
H
Helin Wang 已提交
230
					return C.PSERVER_ERROR
H
Helin Wang 已提交
231
				}
232 233 234
			}
		}

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

H
Helin Wang 已提交
240
	return C.PSERVER_OK
241 242 243
}

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

H
Helin Wang 已提交
253
	return C.PSERVER_OK
254 255 256
}

func main() {} // Required but ignored