You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm restarting the discussion on parameter servers from dask/dask-glm#57
When doing distributed training it is often useful to rapidly update and share parameters between distributed workers. The frequency with which these updates can be shared seems to strongly affect the rate of convergence. The common practice today seems to be to have dedicated nodes within the network that serve as parameter servers, accepting and aggregating updates from workers, and periodically publishing those back out to workers.
Dask's existing task scheduling model is not ideal for this. Every computation or communication checks in with the scheduler, which adds unnecessary network roundtrips and provides a central bottleneck for metadata tracking. To do parameter servers well we probably need to break out of this model and engage more peer-to-peer coordination, without frequent checking in with the scheduler.
Building this infrastructure is not hard, but if possible it would be good to build general machinery that can be used to solve both this problem, and potentially others. I would appreciate having a conversation with a few people to identify what programming and networking constructs might suffice for this.
One general mechanism that might fit this need well is Pub/Sub. Under this construct any worker can join a topic as either a publisher or subscriber (or both). It learns from the scheduler who all of its peers are on that topic. When it publishes data on that topic it sends this data directly to all subscribers (or, in the future, to some subscribers that then forward it along to others). Under this model the parameter subscribes to updates and publishes parameters.
An implementation of a single parameter server might look like the following:
defparameter_server(...):
""" This runs on one special worker """parameters=np.random.random(...)
updates_sub=Sub('updates') # subscribe to updates from workersparameters_pub=Pub('parameters') # publish new parameters to workersasyncdefpublish_parameters():
whilenotshould_stop():
parameters_pub.put(parameters) # maybe send only to a few round-robin instead?awaitgen.sleep(0.01) # maybe control this based on network traffic?get_worker().loop.add_callback(publish_parameters)
fornew_datainupdates_sub:
update(parameters, new_data)
ifshould_stop():
returnparametersdefworker(data: List[np.ndarray], # these correspond to chunks of data from a dask arraylabels: List[np.ndarray]):
""" This runs on each worker and gets the arrays present on that worker """data=np.concat(data)
labels=np.concat(labels)
updates_pub=Pub('updates')
parameters_sub=Sub('parameters')
asyncdefupdate_parameters():
asyncforparamsinparameters_sub:
parameters=paramsget_worker().loop.add_callback(update_parameters)
whilenotshould_stop():
batch=data[np.random.randint(0, len(data))]
result=compute_update(parameters, batch)
updates_pub.put(result)
To be clear Pub and Sub don't exist today, but they could exist tomorrow if this is an appropriate model. If it isn't then we can build something else. Other ideas are welcome.
The common practice today seems to be to have dedicated nodes within the network that serve as parameter servers,
That is common practice, and is what distributed Tensorflow uses.
accepting and aggregating updates from workers, and periodically publishing those back out to workers.
In the vanilla case, we only want to update parameters from the parameters we sent to other workers.
In the most simple use case for distributed tensorflow, each worker passes around some parameter global_step that identifies when parameters was pulled from the parameter server, and gathers updates from a certain number of workers. The update is discarded if the global_step a worker sends back is stale. A good reference for this is "Scaling Distributed Machine Learning with the Parameter Server".
This pub/sub framework LGTM. Is there any way to have a worker subscribe to a topic published by another worker in particular? Something like Sub('foo', worker=1) or Pub('foo', worker='nearest_neighbor'). This could enable some of the distributed algorithms (e.g., where nodes are connected to their neighbors and form a ring).
Two extensions:
Async read/writes could be useful, and enable some new algorithms (e.g., Hogwild!).
Async read/writes := having some mechanism so two workers can write to parameters at the same time, and read partially written results. This is probably best accomplished by using threads.
Gradient coding, which codes the gradient ndarray to some object (typically a dictionary).
Two function are defined: encode: ndarray -> dict and decode: dict -> ndarray so decode(encode(x)) == x (well, or maybe only approximately). This would involve the worker running updates_pub.put(encode(result), and the master running update(parameters, decode(new_data)).
I'm inclined to believe these extensions are best suited for a class interface, at least privately.
In the most simple use case for distributed tensorflow, each worker passes around some parameter global_step that identifies when parameters was pulled from the parameter server, and gathers updates from a certain number of workers. The update is discarded if the global_step a worker sends back is stale.
I encourage people to start thinking aspirationally here, a bit beyond the simplest case.
I was looking at Downpour and also this paper which had different algorithms that I felt were both probably decently well approximated with PubSub. It may be though that my approximations are significant.
Is there any way to have a worker subscribe to a topic published by another worker in particular?
This would be outside of the paradigm of pub/sub but is certainly something that is doable. I expect pubsub to be something like 200-400 lines of code. We can do more things if they are important.
I am not personally familiar with algorithms that are based on ring-like topologies. Is this common?
Async read/writes could be useful
The pseudocode above does async reads/writes. The pub.put commands return immediately. The subscribe commands would block, but are happening in an async block.
Gradient coding, which codes the gradient ndarray to some object
I'm hoping that this is independent of communication patterns and is something that folks like you would feel comfortable writing after pubsub, or whatever network machinery we need, is put in place.
I'm inclined to believe these extensions are best suited for a class interface, at least privately.
This work is likely to happen in two levels:
core dask stuff, like pubsub, which has nothing at all to do with parameter servers
ML stuff, which can be as specialized as is necessary
am not personally familiar with algorithms that are based on ring-like topologies. Is this common?
At least one algorithm depends on a ring-structure, Hogwild++. This is suited for HPC applications, and shows much better speedups than Hogwild as the number of workers grow. I don't think I'd say this is relevant or that distributed ring-like topologies are super common, but they could be useful.
core dask stuff, like pubsub, which has nothing at all to do with parameter servers ... ML stuff, which can be as specialized as is necessary
Pub/sub looks sufficient for parameter servers. Almost everything I said was ML specific.
A draft pubsub implementation is available here: dask/distributed#1999 I suspect that it is still buggy.
I'll work on setting up a mocked out example of the system above and then hopefully others can start playing with things.
My initial experiments show that we have about a 1ms latency when sending messages between workers. I am curious to from people who have an understanding of what kinds of latencies we need to get decent performance in these applications.
1ms latency seems reasonable – latency between cluster nodes for me is (on avg) 0.3ms. I think I'd say it a good first draft, and enough to start experimenting. I can implement a parameter server and look for any bottlenecks.
I'm not surprised to see PyTorch be faster, however I am surprised to see that it can do things in 30us. Some things to check if you're interested:
Try a roundtrip. Rank 0 should send data, then receive that same data in each step. This will avoid things like buffering or async sends from giving an overly optimistic result.
It looks like we're currently bound by serializing and communicating models around. We can balance this out by using larger batches, but that probably affects scalability of training. It would be useful to know how much increasing the batch sizes affects training performance over time.
What is the right way to score a model like this? Perhaps we can have the client periodically pull down a model and score it against some testing dataset and then keep a time series of these scores over time?
The communication scheme this notebook implements is "synchronous with backup workers", which is detailed below.
Do you have any thoughts on asynchronous methods that don't wait for all updates to arrive before modifying the model?
Depends on what you mean by "asynchronous" – either the workers don't wait on each other, or the optimization algorithm can return partially updated models. Figure 5 of the Tensorflow paper has a good depiction of the difference:
Using the "synchronous with backup workers" method will use the users optimization method and allow the workers to operate independently, plus the timing won't be effected by stragglers.
gist.github.com/e57551e451bd633e13009ccce9c6ff67 Feedback on whether or not this is valid would be appreciated
I think this implements Hogwild, where workers blindly run SGD (hence the name). This does have convergence guarantees, but they're fairly weak. They require a model sparsity constraint and a limit on how long the workers can take to update the model.
What is the right way to score a model like this?
Your implementation looks good. I think that'd be the easiest method.
I've timed the parameter server in the notebook Centralized-PS.ipynb@a971d2. The parameter server behind this graph implements the "synchronous communication with backup workers", but without any backup workers (i.e, workers never wait and can repeat gradient computations).
Here's a quick summary from that notebook:
Total optimization time
Optimization time components
/>
The solid lines are the median, the shaded color borders specify the 95% confidence interval. I get this on my local machine (16GB RAM, no GPU) when timing the MNIST PyTorch example (which is unrealistic: gradients take a long time to compute but the model is small).
So, looking at the profile page I see something similar-ish.
Of the 11.50 CPU-seconds it took to run a 4-worker training process
6.2 of those seconds were spent waiting on the actor
1.2 of those seconds were spent loading data
3.3 of those seconds were spent calling train (which itself is roughly 50/50 forward/backward)
There are a couple other tiny things, but not worth mentioning.
There were 215 push calls recorded on the parameter server, which places each of them at around 30ms, which is longer than I'd like. During this time bandwidth on the worker with the actor reached around 50MB/s, which is nowhere near saturating local network speed. The Worker's CPU was being used during this time, mostly on networking overhead and data compression, and a little bit on deserialization.
In isolation a single call to train takes around 10ms and pulling a model takes 9ms (though this is proxied through the scheduler so this is conservative)
There are some things we can do to reduce worker overhead:
Experiment with turning off compression (I'll do this now)
Improve serialization of PyTorch objects so that we get straight memoryviews out quickly
I'm curious though how expensive train calls are going to be normally. Is 10ms typical, or do these become more expensive? It may be that training a batch on MNIST is too fast for dask to be of much use.
Turning compression off results in 380MB/s bandwidth and slightly faster performance overall. Offloading compression to a separate thread seems to get to lower bandwidth and decent performance. This might be the solution longer term. The actor worker is now not quite as hot (event loop taking up around 60% of a CPU) and actor wait time is down to around 4s total.
how expensive train calls are going to be normally. Is 10ms typical, or do these become more expensive?
A good benchmark for this is DAWNBench. Top performing deep learning models have a inference latency of 10ms, and a couple spots down is about 20ms. That means the train call is probably costs 40 or 50ms. The fastest I've seen for training is about 100ms.
It may be that training a batch on MNIST is too fast for dask to be of much use.
Sounds like we scale to a larger model, which isn't too hard. I was only using MNIST as an easy and basic example.
Ah interesting, I hadn't drawn that connection before. So because training is just applying the model + back propagation (which is roughly the same order of magnitude) we would expect something like 2x of the inference cost.
But for a minibatch would we then multiply by the batch size? Or is it generally much cheaper to compute a batch than to compute many samples individually.
But for a minibatch would we then multiply by the batch size? Or is it generally much cheaper to compute a batch than to compute many samples individually.
We can multiply by the batch size. The only cheaper faster way to calculate the gradient is to feed them through a GPU (which is why batch sizes are typically multiples of 32).
Calculating the gradient for many examples requires knowing the how wrong the prediction is on each example, and then adding up their gradients.
training is just applying the model + back propagation (which is roughly the same order of magnitude)
Correct.
Details: the gradient calculation is done via reverse mode autodiff, which typically requires no more than 5-6x more floating point operations for an typical gradient than a function evaluation. On my machine, it takes 2x longer on average to calculate the gradient vs getting the output with PyTorch's (simple) MNIST network.
Interesting, this differs from Griewank. Going back in time a bit...
In 1982 Phil Wolfe [31] made the following observation regarding the ratio between the cost
of evaluating a gradient with n components and the cost of evaluating the underlying scalar
function.
If care is taken in handling quantities which are common to the function and
derivatives, the ratio is usually around 1.5, not n+1. [31]
The main purpose of this article is to demonstrate that Phil Wolfe's observation is in fact
a theorem (with the average 1.5 replaced by an upper bound 5)
Hm... the review paper I referenced cited Griewank and Walther's 2008 textbook Evaluating Derivatives. In this, I couldn't find a claim that c < 6. I only found that c <= 4 on page 85, but I only skimmed. Without a bound on memory access time, this bound grows to c <= 5. This does rely on some (fair) assumptions about the relative cost (e.g., "that a memory access is at least as slow as a multiplication which is in turn at least as slow as an addition").
Activity
mrocklin commentedon May 21, 2018
One general mechanism that might fit this need well is Pub/Sub. Under this construct any worker can join a topic as either a publisher or subscriber (or both). It learns from the scheduler who all of its peers are on that topic. When it publishes data on that topic it sends this data directly to all subscribers (or, in the future, to some subscribers that then forward it along to others). Under this model the parameter subscribes to updates and publishes parameters.
An implementation of a single parameter server might look like the following:
mrocklin commentedon May 21, 2018
To be clear Pub and Sub don't exist today, but they could exist tomorrow if this is an appropriate model. If it isn't then we can build something else. Other ideas are welcome.
stsievert commentedon May 21, 2018
That is common practice, and is what distributed Tensorflow uses.
In the vanilla case, we only want to update
parametersfrom theparameterswe sent to other workers.In the most simple use case for distributed tensorflow, each worker passes around some parameter
global_stepthat identifies whenparameterswas pulled from the parameter server, and gathers updates from a certain number of workers. The update is discarded if theglobal_stepa worker sends back is stale. A good reference for this is "Scaling Distributed Machine Learning with the Parameter Server".This pub/sub framework LGTM. Is there any way to have a worker subscribe to a topic published by another worker in particular? Something like
Sub('foo', worker=1)orPub('foo', worker='nearest_neighbor'). This could enable some of the distributed algorithms (e.g., where nodes are connected to their neighbors and form a ring).Two extensions:
encode: ndarray -> dictanddecode: dict -> ndarraysodecode(encode(x)) == x(well, or maybe only approximately). This would involve the worker runningupdates_pub.put(encode(result), and the master runningupdate(parameters, decode(new_data)).I'm inclined to believe these extensions are best suited for a class interface, at least privately.
mrocklin commentedon May 21, 2018
I encourage people to start thinking aspirationally here, a bit beyond the simplest case.
I was looking at Downpour and also this paper which had different algorithms that I felt were both probably decently well approximated with PubSub. It may be though that my approximations are significant.
This would be outside of the paradigm of pub/sub but is certainly something that is doable. I expect pubsub to be something like 200-400 lines of code. We can do more things if they are important.
I am not personally familiar with algorithms that are based on ring-like topologies. Is this common?
The pseudocode above does async reads/writes. The pub.put commands return immediately. The subscribe commands would block, but are happening in an async block.
I'm hoping that this is independent of communication patterns and is something that folks like you would feel comfortable writing after pubsub, or whatever network machinery we need, is put in place.
This work is likely to happen in two levels:
stsievert commentedon May 21, 2018
Got it. This makes more sense now.
At least one algorithm depends on a ring-structure, Hogwild++. This is suited for HPC applications, and shows much better speedups than Hogwild as the number of workers grow. I don't think I'd say this is relevant or that distributed ring-like topologies are super common, but they could be useful.
Pub/sub looks sufficient for parameter servers. Almost everything I said was ML specific.
mrocklin commentedon May 23, 2018
A draft pubsub implementation is available here: dask/distributed#1999 I suspect that it is still buggy.
I'll work on setting up a mocked out example of the system above and then hopefully others can start playing with things.
My initial experiments show that we have about a 1ms latency when sending messages between workers. I am curious to from people who have an understanding of what kinds of latencies we need to get decent performance in these applications.
stsievert commentedon May 23, 2018
Moderate sized deep learning models have latency of at least 10ms for feeding 1 image through the network for prediction (source: https://dawn.cs.stanford.edu/benchmark/). The time required for optimization of these networks is (likely) no more than 5-6 times as slow, so probably at least 50-100ms for one optimization step.
mrocklin commentedon May 23, 2018
stsievert commentedon May 23, 2018
1ms latency seems reasonable – latency between cluster nodes for me is (on avg) 0.3ms. I think I'd say it a good first draft, and enough to start experimenting. I can implement a parameter server and look for any bottlenecks.
mrocklin commentedon May 28, 2018
PubSub is merged. I have a tiny toy example here: https://gist.github.com/mrocklin/0d906828544ddeb8e6e1d3d193172ae9
stsievert commentedon Jun 8, 2018
@mrocklin could I have your timing script to measure the latency? I'd like to compare on the same machine. I'm measuring the latency of PyTorch's
distributedmodule to have a latency of 0.029ms with https://gist.github.com/stsievert/1a93cf732d66f22a3080fcd0729364d6mrocklin commentedon Jun 10, 2018
stsievert commentedon Jun 10, 2018
Side by side on my machine I measure PyTorch 0.4.0 to have a latency of 0.031ms and dask.distributed master to have a latency of 1.398ms, both between two processes with Python 3.6.5. I measure with the same gist, https://gist.github.com/stsievert/1a93cf732d66f22a3080fcd0729364d6
mrocklin commentedon Jun 10, 2018
I'm not surprised to see PyTorch be faster, however I am surprised to see that it can do things in 30us. Some things to check if you're interested:
stsievert commentedon Jun 11, 2018
I measure a latency of 16us with Python 3.6.5 and 19us with Python 2.7.5 for the code in the updated gist. I've slightly modified the example from https://pymotw.com/3/socket/tcp.html.
For PyTorch with a roundtrip, I'm measuring a latency of 37us.
25 remaining items
mrocklin commentedon Aug 7, 2018
It looks like we're currently bound by serializing and communicating models around. We can balance this out by using larger batches, but that probably affects scalability of training. It would be useful to know how much increasing the batch sizes affects training performance over time.
What is the right way to score a model like this? Perhaps we can have the client periodically pull down a model and score it against some testing dataset and then keep a time series of these scores over time?
mrocklin commentedon Aug 7, 2018
As in the following:
stsievert commentedon Aug 7, 2018
I've reworked your notebook: https://github.com/stsievert/dask-ps/blob/master/Centralized-PS.ipynb. This notebook is functionally the same as my previous implementation, but it spends less time waiting. I'm not sure why.
The communication scheme this notebook implements is "synchronous with backup workers", which is detailed below.
Depends on what you mean by "asynchronous" – either the workers don't wait on each other, or the optimization algorithm can return partially updated models. Figure 5 of the Tensorflow paper has a good depiction of the difference:
Using the "synchronous with backup workers" method will use the users optimization method and allow the workers to operate independently, plus the timing won't be effected by stragglers.
More of this difference and the performance benefits are detailed in "Revisiting distributed synchronous SGD".
I think this implements Hogwild, where workers blindly run SGD (hence the name). This does have convergence guarantees, but they're fairly weak. They require a model sparsity constraint and a limit on how long the workers can take to update the model.
Your implementation looks good. I think that'd be the easiest method.
stsievert commentedon Aug 8, 2018
I've timed the parameter server in the notebook Centralized-PS.ipynb@a971d2. The parameter server behind this graph implements the "synchronous communication with backup workers", but without any backup workers (i.e, workers never wait and can repeat gradient computations).
Here's a quick summary from that notebook:
The solid lines are the median, the shaded color borders specify the 95% confidence interval. I get this on my local machine (16GB RAM, no GPU) when timing the MNIST PyTorch example (which is unrealistic: gradients take a long time to compute but the model is small).
mrocklin commentedon Aug 8, 2018
So, looking at the profile page I see something similar-ish.
Of the 11.50 CPU-seconds it took to run a 4-worker training process
There are a couple other tiny things, but not worth mentioning.
There were 215 push calls recorded on the parameter server, which places each of them at around 30ms, which is longer than I'd like. During this time bandwidth on the worker with the actor reached around 50MB/s, which is nowhere near saturating local network speed. The Worker's CPU was being used during this time, mostly on networking overhead and data compression, and a little bit on deserialization.
In isolation a single call to train takes around 10ms and pulling a model takes 9ms (though this is proxied through the scheduler so this is conservative)
mrocklin commentedon Aug 8, 2018
There are some things we can do to reduce worker overhead:
I'm curious though how expensive train calls are going to be normally. Is 10ms typical, or do these become more expensive? It may be that training a batch on MNIST is too fast for dask to be of much use.
mrocklin commentedon Aug 8, 2018
Turning compression off results in 380MB/s bandwidth and slightly faster performance overall. Offloading compression to a separate thread seems to get to lower bandwidth and decent performance. This might be the solution longer term. The actor worker is now not quite as hot (event loop taking up around 60% of a CPU) and actor wait time is down to around 4s total.
stsievert commentedon Aug 8, 2018
A good benchmark for this is DAWNBench. Top performing deep learning models have a inference latency of 10ms, and a couple spots down is about 20ms. That means the
traincall is probably costs 40 or 50ms. The fastest I've seen for training is about 100ms.Sounds like we scale to a larger model, which isn't too hard. I was only using MNIST as an easy and basic example.
mrocklin commentedon Aug 8, 2018
Ah interesting, I hadn't drawn that connection before. So because training is just applying the model + back propagation (which is roughly the same order of magnitude) we would expect something like 2x of the inference cost.
But for a minibatch would we then multiply by the batch size? Or is it generally much cheaper to compute a batch than to compute many samples individually.
stsievert commentedon Aug 9, 2018
We can multiply by the batch size. The only
cheaperfaster way to calculate the gradient is to feed them through a GPU (which is why batch sizes are typically multiples of 32).Calculating the gradient for many examples requires knowing the how wrong the prediction is on each example, and then adding up their gradients.
Correct.
Details: the gradient calculation is done via reverse mode autodiff, which typically requires no more than 5-6x more floating point operations for an typical gradient than a function evaluation. On my machine, it takes 2x longer on average to calculate the gradient vs getting the output with PyTorch's (simple) MNIST network.
(also, turns out autodiff is faster than hard-coding the gradient with NumPy even though it does more work because the graph autodiff requires can be parallelized: https://stsievert.com/blog/2017/09/07/pytorch/#speed)
mrocklin commentedon Aug 9, 2018
Heh, not just typically. My understanding is that the 5x number is part of a theorem in the early work on the subject :)
1-2x matches my experience as well, though obviously this depends on the system you use. There is a lot of fun work in that field to suit all sorts :)
stsievert commentedon Aug 9, 2018
Almost – you're off by one! It's guaranteed to be strictly less than 6:
mrocklin commentedon Aug 9, 2018
Interesting, this differs from Griewank. Going back in time a bit...
In 1982 Phil Wolfe [31] made the following observation regarding the ratio between the cost
of evaluating a gradient with n components and the cost of evaluating the underlying scalar
function.
The main purpose of this article is to demonstrate that Phil Wolfe's observation is in fact
a theorem (with the average 1.5 replaced by an upper bound 5)
https://www.researchgate.net/profile/Andreas_Griewank/publication/2703247_On_Automatic_Differentiation/links/0c96052529013aed9e000000/On-Automatic-Differentiation.pdf
stsievert commentedon Aug 9, 2018
Hm... the review paper I referenced cited Griewank and Walther's 2008 textbook Evaluating Derivatives. In this, I couldn't find a claim that c < 6. I only found that c <= 4 on page 85, but I only skimmed. Without a bound on memory access time, this bound grows to c <= 5. This does rely on some (fair) assumptions about the relative cost (e.g., "that a memory access is at least as slow as a multiplication which is in turn at least as slow as an addition").
Thanks for the reference.