optimizer.go 3.7 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/inconshreveable/log15"
29 30 31
)

type optimizer struct {
D
dongzhihong 已提交
32 33
	opt         *C.struct_paddle_optimizer
	elementType ElementType
34
	contentLen  int
H
Helin Wang 已提交
35
	config      []byte
D
dongzhihong 已提交
36 37 38
}

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

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

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

H
Helin Wang 已提交
74 75 76 77
	var cptr (*C.uchar)
	if len(c) > 0 {
		cptr = (*C.uchar)(&c[0])
	}
H
Helin Wang 已提交
78
	o.config = c
79
	o.opt = C.paddle_create_optimizer(
H
Helin Wang 已提交
80
		cptr,
81 82 83 84 85 86 87
		C.int(len(c)),
		C.paddle_element_type(p.ElementType),
		cbuffer,
		C.int(paramBufferSize),
		(*C.char)(cstate),
		C.int(len(s)),
	)
88 89 90
	return o
}

91
func (o *optimizer) GetWeights() []byte {
D
dongzhihong 已提交
92
	var buffer unsafe.Pointer
93
	// we do not own the buffer, no need to free later.
W
wuyi05 已提交
94 95
	bufferLen := C.paddle_optimizer_get_weights(o.opt, &buffer)
	return cArrayToSlice(buffer, int(bufferLen)*C.sizeof_float)
D
dongzhihong 已提交
96
}
97

D
dongzhihong 已提交
98 99
func (o *optimizer) GetStates() []byte {
	var cbuffer *C.char
100
	// we owns the state buffer, need to free later.
101
	cbufferLen := C.paddle_optimizer_get_state(o.opt, &cbuffer)
102 103 104 105 106
	buf := cArrayToSlice(unsafe.Pointer(cbuffer), int(cbufferLen))
	cpy := make([]byte, len(buf))
	copy(cpy, buf)
	C.free(unsafe.Pointer(cbuffer))
	return cpy
D
dongzhihong 已提交
107 108
}

D
dongzhihong 已提交
109
func (o *optimizer) UpdateParameter(g Gradient) error {
D
dongzhihong 已提交
110 111
	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)
112 113
	}

114 115 116 117 118
	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)))
119
	if r != 0 {
H
Helin Wang 已提交
120
		return fmt.Errorf("optimizer update returned error code: %d", r)
121 122 123 124 125
	}
	return nil
}

func (o *optimizer) Cleanup() {
126
	if unsafe.Pointer(o.opt) != nil {
127
		C.paddle_release_optimizer(o.opt)
128
		o.opt = (*C.struct_paddle_optimizer)(nil)
129 130
	}
}