optimizer.go 3.4 KB
Newer Older
D
dongzhihong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15 16
package pserver

D
dongzhihong 已提交
17
// #cgo CFLAGS: -I ../../
18
// #cgo LDFLAGS: ${SRCDIR}/client/c/libpaddle_go_optimizer.a -lstdc++ -lm
D
dongzhihong 已提交
19 20 21
// #include "paddle/optimizer/optimizer.h"
// #include <stdlib.h>
// #include <string.h>
22
import "C"
D
dongzhihong 已提交
23

24 25 26
import (
	"fmt"
	"unsafe"
D
dongzhihong 已提交
27 28

	log "github.com/sirupsen/logrus"
29 30 31
)

type optimizer struct {
D
dongzhihong 已提交
32 33
	opt         *C.struct_paddle_optimizer
	elementType ElementType
34
	contentLen  int
D
dongzhihong 已提交
35 36 37
}

func cArrayToSlice(p unsafe.Pointer, len int) []byte {
38
	if p == nil {
D
dongzhihong 已提交
39 40 41 42 43 44 45 46 47
		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]
48 49
}

D
dongzhihong 已提交
50
func newOptimizer(paramWithConfigs ParameterWithConfig, State []byte) *optimizer {
51
	o := &optimizer{}
D
dongzhihong 已提交
52
	o.elementType = paramWithConfigs.Param.ElementType
53
	o.contentLen = len(paramWithConfigs.Param.Content)
D
dzhwinter 已提交
54 55
	p := paramWithConfigs.Param
	c := paramWithConfigs.Config
D
dongzhihong 已提交
56
	s := State
57
	paramBufferSize := C.size_t(len(p.Content))
D
dongzhihong 已提交
58 59
	log.WithFields(log.Fields{
		"ElementType": p.ElementType,
60
		"ParamSize":   paramBufferSize,
D
dongzhihong 已提交
61
		"ConfigSize":  len(c),
D
dongzhihong 已提交
62
		"StateSize":   len(s),
D
dongzhihong 已提交
63
	}).Info("New Optimizer Created with config:")
D
dongzhihong 已提交
64
	var cbuffer unsafe.Pointer
65 66 67
	cbuffer = C.malloc(paramBufferSize)

	C.memcpy(cbuffer, unsafe.Pointer(&p.Content[0]), paramBufferSize)
D
dongzhihong 已提交
68 69 70 71 72
	var cstate unsafe.Pointer
	if len(s) != 0 {
		cstate = unsafe.Pointer(&s[0])
	}

D
dongzhihong 已提交
73
	o.opt = C.paddle_create_optimizer((*C.uchar)(&c[0]), C.int(len(c)),
74
		C.paddle_element_type(p.ElementType), cbuffer, C.int(paramBufferSize), (*C.char)(cstate), C.int(len(s)))
75 76 77
	return o
}

78
func (o *optimizer) GetWeights() []byte {
D
dongzhihong 已提交
79
	var buffer unsafe.Pointer
W
wuyi05 已提交
80 81
	bufferLen := C.paddle_optimizer_get_weights(o.opt, &buffer)
	return cArrayToSlice(buffer, int(bufferLen)*C.sizeof_float)
D
dongzhihong 已提交
82
}
83

D
dongzhihong 已提交
84 85
func (o *optimizer) GetStates() []byte {
	var cbuffer *C.char
86 87
	cbufferLen := C.paddle_optimizer_get_state(o.opt, &cbuffer)
	return cArrayToSlice(unsafe.Pointer(cbuffer), int(cbufferLen))
D
dongzhihong 已提交
88 89
}

D
dongzhihong 已提交
90
func (o *optimizer) UpdateParameter(g Gradient) error {
D
dongzhihong 已提交
91 92
	if o.elementType != g.ElementType {
		return fmt.Errorf("Name: %s, parameter and gradient element type not match, parameter: %v, gradient: %v", g.Name, o.elementType, g.ElementType)
93 94
	}

95 96 97 98 99
	if o.contentLen != len(g.Content) {
		return fmt.Errorf("Name: %s, parameter and gradient does not have same content len, parameter: %d, gradient: %d", g.Name, o.contentLen, len(g.Content))
	}

	r := C.paddle_update_parameter(o.opt, C.paddle_element_type(g.ElementType), unsafe.Pointer(&g.Content[0]), C.int(len(g.Content)))
100
	if r != 0 {
H
Helin Wang 已提交
101
		return fmt.Errorf("optimizer update returned error code: %d", r)
102 103 104 105 106
	}
	return nil
}

func (o *optimizer) Cleanup() {
107
	if unsafe.Pointer(o.opt) != nil {
108
		C.paddle_release_optimizer(o.opt)
109
		o.opt = (*C.struct_paddle_optimizer)(nil)
110 111
	}
}