client.go 5.1 KB
Newer Older
1 2
package pserver

3
import (
D
dongzhihong 已提交
4
	"errors"
5 6 7 8
	"hash/fnv"
	"sort"
	"time"

9
	"github.com/PaddlePaddle/Paddle/go/connection"
H
Helin Wang 已提交
10
	log "github.com/sirupsen/logrus"
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
)

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

// Selector selects if the client should initialize parameter servers.
type Selector interface {
	Select() bool
}

// 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 已提交
31
// Client is the client to parameter servers.
32
type Client struct {
33 34
	sel      Selector
	pservers []*connection.Conn
35 36
}

H
Helin Wang 已提交
37
// NewClient creates a new client.
38 39 40 41 42 43 44 45 46 47 48 49 50
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) {
51
	lastServers := make([]Server, pserverNum)
52 53 54 55 56 57 58 59
	ticker := time.NewTicker(10 * time.Second)
	monitor := func() {
		curServers := make([]Server, pserverNum)
		list := l.List()
		for _, l := range list {
			curServers[l.Index] = l
		}

60
		for i := range lastServers {
H
Helin Wang 已提交
61 62 63
			if lastServers[i].Addr == curServers[i].Addr {
				continue
			}
64

H
Helin Wang 已提交
65 66
			if curServers[i].Addr == "" {
				err := c.pservers[i].Close()
67
				if err != nil {
H
Helin Wang 已提交
68
					log.Errorln(err)
69
				}
H
Helin Wang 已提交
70 71

				continue
72
			}
H
Helin Wang 已提交
73 74 75

			err := c.pservers[i].Connect(curServers[i].Addr)
			if err != nil {
H
Helin Wang 已提交
76
				log.Errorln(err)
H
Helin Wang 已提交
77 78 79 80 81 82 83

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

84 85
		}

86
		lastServers = curServers
87 88 89
	}

	monitor()
H
Helin Wang 已提交
90
	for range ticker.C {
91 92
		monitor()
	}
93 94
}

H
Helin Wang 已提交
95 96 97 98 99 100 101 102
// 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.
103 104
func (c *Client) BeginInitParams() bool {
	return c.sel.Select()
105 106
}

H
Helin Wang 已提交
107
// InitParam initializes the parameter on parameter servers.
108
func (c *Client) InitParam(paramWithConfigs ParameterWithConfig) error {
109
	return c.pservers[c.partition(paramWithConfigs.Param.Name)].Call("Service.InitParam", paramWithConfigs, nil)
110 111
}

H
Helin Wang 已提交
112 113
// FinishInitParams tells parameter servers client has sent all
// parameters to parameter servers as initialization.
114
func (c *Client) FinishInitParams() error {
115
	for _, p := range c.pservers {
116
		err := p.Call("Service.FinishInitParams", 0, nil)
117 118 119 120
		if err != nil {
			return err
		}
	}
121 122 123
	return nil
}

H
Helin Wang 已提交
124 125
// SendGrads sends gradients to parameter servers for updating
// parameters.
126
func (c *Client) SendGrads(grads []Gradient) error {
127
	if len(grads) == 0 {
D
dongzhihong 已提交
128
		return errors.New("no gradient received")
129
	}
130 131 132
	errCh := make(chan error, len(grads))
	for _, g := range grads {
		go func(g Gradient) {
133
			err := c.pservers[c.partition(g.Name)].Call("Service.SendGrad", g, nil)
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
			errCh <- err
		}(g)
	}

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

		recv++
		if recv == len(grads) {
			break
		}
	}
149 150 151
	return nil
}

152
type result struct {
H
Helin Wang 已提交
153 154 155
	idx   int
	param Parameter
	err   error
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
}

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 已提交
172
// GetParams gets parameters from parameter servers.
173
func (c *Client) GetParams(names []string) ([]Parameter, error) {
174 175 176 177 178 179
	rCh := make(chan result, len(names))

	for idx, name := range names {
		go func(name string, idx int) {
			var parameter Parameter
			err := c.pservers[c.partition(name)].Call("Service.GetParam", name, &parameter)
H
Helin Wang 已提交
180
			rCh <- result{idx: idx, param: parameter, err: err}
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
		}(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)

	ps := make([]Parameter, len(rs))
	for i := range rs {
H
Helin Wang 已提交
201
		ps[i] = rs[i].param
202 203 204
	}

	return ps, nil
205 206
}

207 208 209 210 211
// Save indicates parameters to save the parameter to the given path.
func (c *Client) Save(path string) error {
	errCh := make(chan error, len(c.pservers))

	for _, p := range c.pservers {
212
		err := p.Call("Service.Save", path, nil)
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
		errCh <- err
	}

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

		recv++
		if recv == len(c.pservers) {
			break
		}
	}

	// TODO(helin): there will be many files under path, need to
	// merge them into a single file.
230 231 232
	return nil
}

233 234 235 236 237 238 239 240 241 242 243
func strHash(s string) uint32 {
	h := fnv.New32a()
	h.Write([]byte(s))
	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)))
244
}