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

// 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.

Q
Qiao Longfei 已提交
15
package client
16

17
import (
D
dongzhihong 已提交
18
	"errors"
19 20 21 22
	"hash/fnv"
	"sort"
	"time"

23
	"github.com/PaddlePaddle/Paddle/go/connection"
Q
Qiao Longfei 已提交
24
	"github.com/PaddlePaddle/Paddle/go/pserver"
25
	log "github.com/inconshreveable/log15"
26 27 28 29
)

// TODO(helin): add RPC call retry logic

30 31
// Selector selects if the client should initialize parameters and
// reports the initialization process done.
32
type Selector interface {
33 34 35 36
	// Select selects if the client should initialize parameter servers.
	Select() (bool, error)
	// Done indicates the initialization process is done.
	Done() error
37 38 39 40 41 42 43 44 45 46 47 48 49
}

// Server is the identification of a parameter Server.
type Server struct {
	Index int
	Addr  string
}

// Lister lists currently available parameter servers.
type Lister interface {
	List() []Server
}

H
Helin Wang 已提交
50
// Client is the client to parameter servers.
51
type Client struct {
52 53
	sel      Selector
	pservers []*connection.Conn
54 55
}

H
Helin Wang 已提交
56
// NewClient creates a new client.
57 58 59 60 61 62 63 64 65 66 67 68 69
func NewClient(l Lister, pserverNum int, sel Selector) *Client {
	c := &Client{sel: sel}
	c.pservers = make([]*connection.Conn, pserverNum)
	for i := 0; i < pserverNum; i++ {
		c.pservers[i] = connection.New()
	}
	go c.monitorPservers(l, pserverNum)
	return c
}

// monitorPservers monitors pserver addresses, and updates connection
// when the address changes.
func (c *Client) monitorPservers(l Lister, pserverNum int) {
70
	lastServers := make([]Server, pserverNum)
71 72 73 74 75 76 77 78
	ticker := time.NewTicker(10 * time.Second)
	monitor := func() {
		curServers := make([]Server, pserverNum)
		list := l.List()
		for _, l := range list {
			curServers[l.Index] = l
		}

79
		for i := range lastServers {
H
Helin Wang 已提交
80 81 82
			if lastServers[i].Addr == curServers[i].Addr {
				continue
			}
83

H
Helin Wang 已提交
84 85
			if curServers[i].Addr == "" {
				err := c.pservers[i].Close()
86
				if err != nil {
87
					log.Error("error closing connection to pserver", log.Ctx{"error": err})
88
				}
H
Helin Wang 已提交
89 90

				continue
91
			}
H
Helin Wang 已提交
92 93 94

			err := c.pservers[i].Connect(curServers[i].Addr)
			if err != nil {
95
				log.Error("error connecting to pserver", log.Ctx{"error": err})
H
Helin Wang 已提交
96 97 98 99 100 101 102

				// connect to addr failed, set
				// to last known addr in order
				// to retry next time.
				curServers[i].Addr = lastServers[i].Addr
			}

103 104
		}

105
		lastServers = curServers
106 107 108
	}

	monitor()
H
Helin Wang 已提交
109
	for range ticker.C {
110 111
		monitor()
	}
112 113
}

H
Helin Wang 已提交
114 115 116 117 118 119 120 121
// BeginInitParams begins to initialize parameters on parameter
// servers.
//
// BeginInitParams will be called from multiple trainers, only one
// trainer will be selected to initialize the parameters on parameter
// servers. Other trainers will be blocked until the initialization is
// done, and they need to get the initialized parameters from
// parameter servers using GetParams.
122
func (c *Client) BeginInitParams() (bool, error) {
123
	return c.sel.Select()
124 125
}

H
Helin Wang 已提交
126
// InitParam initializes the parameter on parameter servers.
Q
Qiao Longfei 已提交
127
func (c *Client) InitParam(paramWithConfigs pserver.ParameterWithConfig) error {
128
	return c.pservers[c.partition(paramWithConfigs.Param.Name)].Call("Service.InitParam", paramWithConfigs, nil)
129 130
}

H
Helin Wang 已提交
131 132
// FinishInitParams tells parameter servers client has sent all
// parameters to parameter servers as initialization.
133
func (c *Client) FinishInitParams() error {
134
	for _, p := range c.pservers {
135
		err := p.Call("Service.FinishInitParams", 0, nil)
136 137 138 139
		if err != nil {
			return err
		}
	}
武毅 已提交
140
	return c.sel.Done()
141 142
}

H
Helin Wang 已提交
143 144
// SendGrads sends gradients to parameter servers for updating
// parameters.
Q
Qiao Longfei 已提交
145
func (c *Client) SendGrads(grads []pserver.Gradient) error {
146
	if len(grads) == 0 {
D
dongzhihong 已提交
147
		return errors.New("no gradient received")
148
	}
149 150
	errCh := make(chan error, len(grads))
	for _, g := range grads {
Q
Qiao Longfei 已提交
151
		go func(g pserver.Gradient) {
152
			err := c.pservers[c.partition(g.Name)].Call("Service.SendGrad", g, nil)
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
			errCh <- err
		}(g)
	}

	recv := 0
	for err := range errCh {
		if err != nil {
			return err
		}

		recv++
		if recv == len(grads) {
			break
		}
	}
168 169 170
	return nil
}

171
type result struct {
H
Helin Wang 已提交
172
	idx   int
Q
Qiao Longfei 已提交
173
	param pserver.Parameter
H
Helin Wang 已提交
174
	err   error
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
}

type results []result

func (r results) Len() int {
	return len(r)
}

func (r results) Less(i int, j int) bool {
	return r[i].idx < r[j].idx
}

func (r results) Swap(i int, j int) {
	r[i], r[j] = r[j], r[i]
}

H
Helin Wang 已提交
191
// GetParams gets parameters from parameter servers.
Q
Qiao Longfei 已提交
192
func (c *Client) GetParams(names []string) ([]pserver.Parameter, error) {
193 194 195 196
	rCh := make(chan result, len(names))

	for idx, name := range names {
		go func(name string, idx int) {
Q
Qiao Longfei 已提交
197
			var parameter pserver.Parameter
198
			err := c.pservers[c.partition(name)].Call("Service.GetParam", name, &parameter)
H
Helin Wang 已提交
199
			rCh <- result{idx: idx, param: parameter, err: err}
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
		}(name, idx)
	}

	var rs results
	recv := 0
	for r := range rCh {
		if r.err != nil {
			return nil, r.err
		}
		rs = append(rs, r)

		recv++
		if recv == len(names) {
			break
		}
	}
	sort.Sort(rs)

Q
Qiao Longfei 已提交
218
	ps := make([]pserver.Parameter, len(rs))
219
	for i := range rs {
H
Helin Wang 已提交
220
		ps[i] = rs[i].param
221 222 223
	}

	return ps, nil
224 225
}

226 227
func strHash(s string) uint32 {
	h := fnv.New32a()
H
Helin Wang 已提交
228
	_, _ = h.Write([]byte(s))
229 230 231 232 233 234 235 236
	return h.Sum32()
}

// TODO(helin): now partition only select which parameter server to
// send the entire parameter. We need to partition a parameter into
// small blocks and send to different parameter servers.
func (c *Client) partition(key string) int {
	return int(strHash(key) % uint32(len(c.pservers)))
237
}