optimizer.go 2.3 KB
Newer Older
1 2 3
package pserver

/*
D
dzhwinter 已提交
4 5
// TODO(zhihong): move compile flags to cmake go_library
#cgo pkg-config: protobuf
D
dzhwinter 已提交
6
#cgo CFLAGS: -I ../../
D
dongzhihong 已提交
7
#cgo LDFLAGS: /Users/dzh/.go/src/github.com/PaddlePaddle/Paddle/build/go/pserver/cclient/libpaddle_go_optimizer.a -lstdc++
D
dzhwinter 已提交
8
#include "paddle/optimizer/optimizer.h"
9 10 11 12 13 14 15 16 17 18
*/
import "C"
import (
	"fmt"
	"unsafe"
)

var nullPtr = unsafe.Pointer(uintptr(0))

type optimizer struct {
19
	opt *C.struct_paddle_optimizer
D
dongzhihong 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
	// used in GetParam, reconstruct Parameter from optimizer
	ElementType ElementType
}

func cArrayToSlice(p unsafe.Pointer, len int) []byte {
	if p == nullPtr {
		return nil
	}

	// 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
	// to be freed properly.
	return (*[1 << 30]byte)(p)[:len:len]
35 36
}

D
dzhwinter 已提交
37
func newOptimizer(paramWithConfigs ParameterWithConfig) *optimizer {
38
	o := &optimizer{}
D
dzhwinter 已提交
39 40
	p := paramWithConfigs.Param
	c := paramWithConfigs.Config
D
dongzhihong 已提交
41 42 43 44 45
	var cbuffer unsafe.Pointer
	cbuffer = unsafe.Pointer(&p.Content[0])
	o.opt = C.paddle_create_optimizer((*C.uchar)(&c[0]), C.int(len(c)),
		C.paddle_element_type(p.ElementType), cbuffer, C.int(len(p.Content)),
		(*C.char)(nullPtr), 0)
46 47 48
	return o
}

D
dongzhihong 已提交
49 50 51
func (o *optimizer) GetWeights(p *Parameter) error {

	var buffer unsafe.Pointer
D
dongzhihong 已提交
52
	buffer_len := C.paddle_optimizer_get_weights(o.opt, &buffer)
D
dongzhihong 已提交
53
	if buffer_len == 0 || buffer == nullPtr {
D
dongzhihong 已提交
54
		return fmt.Errorf("parameter optimizer error : %s get failed", p.Name)
55
	}
D
dongzhihong 已提交
56 57 58
	p.Content = cArrayToSlice(buffer, int(buffer_len))
	return nil
}
59

D
dongzhihong 已提交
60 61 62
func (o *optimizer) UpdateParameter(g Gradient) error {
	if o.ElementType != g.ElementType {
		return fmt.Errorf("Name: %s, parameter and gradient element type not match, parameter: %v, gradient: %v", g.Name, g.ElementType, g.ElementType)
63 64
	}

D
dongzhihong 已提交
65
	// FIXME: do we need a copy? discard g.Content by GC ok
D
dongzhihong 已提交
66 67 68
	var cbuffer unsafe.Pointer
	cbuffer = unsafe.Pointer(&g.Content[0])
	r := C.paddle_update_parameter(o.opt, C.paddle_element_type(g.ElementType), cbuffer, C.int(len(g.Content)))
69
	if r != 0 {
H
Helin Wang 已提交
70
		return fmt.Errorf("optimizer update returned error code: %d", r)
71 72 73 74 75 76 77
	}
	return nil
}

func (o *optimizer) Cleanup() {
	if unsafe.Pointer(o.opt) != nullPtr {
		C.paddle_release_optimizer(o.opt)
78
		o.opt = (*C.struct_paddle_optimizer)(nullPtr)
79 80
	}
}