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

/*
D
dzhwinter 已提交
4
#cgo CFLAGS: -I ../../
D
dzhwinter 已提交
5
#include "paddle/optimizer/optimizer.h"
6 7 8 9 10 11 12 13 14 15
*/
import "C"
import (
	"fmt"
	"unsafe"
)

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

type optimizer struct {
16
	opt *C.struct_paddle_optimizer
17 18
}

D
dzhwinter 已提交
19
func newOptimizer(paramWithConfigs ParameterWithConfig) *optimizer {
20
	o := &optimizer{}
D
dzhwinter 已提交
21 22 23
	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)
24 25 26 27
	return o
}

func (o *optimizer) UpdateParameter(p Parameter, g Gradient) error {
D
dzhwinter 已提交
28 29
	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)
30 31 32
	}

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

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

func (o *optimizer) Cleanup() {
	if unsafe.Pointer(o.opt) != nullPtr {
		C.paddle_release_optimizer(o.opt)
46
		o.opt = (*C.struct_paddle_optimizer)(nullPtr)
47 48
	}
}