optimizer.go 1.7 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
dzhwinter 已提交
7
#cgo LDFLAGS: ../../build/paddle/optimizer/libpaddle_optimizer.a ../../build/proto/libpaddle_proto.a ../../third_party/install/glog/lib/libglog.a ../../third_party/install/gtest/lib/libgtest.a ../../third_party/install/gflags/lib/libgflags.a ../../third_party/install/openblas/lib/libopenblas.a -I/usr/local/lib/ -lprotobuf
D
dzhwinter 已提交
8
#cgo LDFLAGS: /Users/dzh/.go/src/github.com/PaddlePaddle/Paddle/build/lib/libdep.a
D
dzhwinter 已提交
9
#include "paddle/optimizer/optimizer.h"
10 11 12 13 14 15 16 17 18 19
*/
import "C"
import (
	"fmt"
	"unsafe"
)

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

type optimizer struct {
20
	opt *C.struct_paddle_optimizer
21 22
}

D
dzhwinter 已提交
23
func newOptimizer(paramWithConfigs ParameterWithConfig) *optimizer {
24
	o := &optimizer{}
D
dzhwinter 已提交
25 26 27
	p := paramWithConfigs.Param
	c := paramWithConfigs.Config
	o.opt = C.paddle_create_optimizer(C.uchar(c), C.int(len(c)), unsafe.Pointer(p.Content), c.int(p.Length), nullPtr, 0)
28 29 30 31
	return o
}

func (o *optimizer) UpdateParameter(p Parameter, g Gradient) error {
D
dzhwinter 已提交
32 33
	if p.Length != g.Length {
		return fmt.Errorf("Name: %s, parameter and gradient length not match, parameter: %d, gradient: %d", p.Name, p.Length, g.Length)
34 35 36
	}

	if p.ElementType != g.ElementType {
37
		return fmt.Errorf("Name: %s, parameter and gradient element type not match, parameter: %v, gradient: %v", p.Name, p.ElementType, g.ElementType)
38 39
	}

D
dzhwinter 已提交
40
	r := C.paddle_update_parameter(o.opt, C.paddle_element_type(p.ElementType), unsafe.Pointer(g.Content), C.int(g.Length))
41
	if r != 0 {
H
Helin Wang 已提交
42
		return fmt.Errorf("optimizer update returned error code: %d", r)
43 44 45 46 47 48 49
	}
	return nil
}

func (o *optimizer) Cleanup() {
	if unsafe.Pointer(o.opt) != nullPtr {
		C.paddle_release_optimizer(o.opt)
50
		o.opt = (*C.struct_paddle_optimizer)(nullPtr)
51 52
	}
}