---
title: "TF-Replicator: Distributed Machine Learning for Researchers"
description: "TF-Replicator lets researchers move TensorFlow training across GPUs and TPUs while keeping control of their computation and training loop."
canonical: "https://research.elamur.ai/free/en/papers/buchlovsky-2019-tf-replicator-distributed-machine-learning/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/) · [Constitution](https://md.constitution.elamur.ai/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/buchlovsky-2019-tf-replicator-distributed-machine-learning/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2019](https://md.research.elamur.ai/free/en/papers/2019/) / TF-Replicator: Distributed Machine Learning for Researchers

# TF-Replicator: Distributed Machine Learning for Researchers

Paper · 2019 · Peter Buchlovsky, David Budden, Dominik Grewe et al.

**Authors:** Peter Buchlovsky, [David Budden](https://md.research.elamur.ai/free/en/authors/david-budden/), [Dominik Grewe](https://md.research.elamur.ai/free/en/authors/dominik-grewe/), [Chris Jones](https://md.research.elamur.ai/free/en/authors/chris-jones/), [John Aslanides](https://md.research.elamur.ai/free/en/authors/john-aslanides/), Frederic Besse, [Andy Brock](https://md.research.elamur.ai/free/en/authors/andy-brock/), [Aidan Clark](https://md.research.elamur.ai/free/en/authors/aidan-clark/), Sergio Gomez Colmenarejo, [Aedan Pope](https://md.research.elamur.ai/free/en/authors/aedan-pope/), [Fabio Viola](https://md.research.elamur.ai/free/en/authors/fabio-viola/) and [Dan Belov](https://md.research.elamur.ai/free/en/authors/dan-belov/) · **Year:** 2019 · **Venue:** arXiv:1902.00465 · **Licence:** [arXiv — non-exclusive license to distribute](http://arxiv.org/licenses/nonexclusive-distrib/1.0/)

[licence](http://arxiv.org/licenses/nonexclusive-distrib/1.0/)

- [PDF](https://arxiv.org/pdf/1902.00465)
- [arXiv 1902.00465](https://arxiv.org/abs/1902.00465)

## Summary

A training program that works on a single accelerator can be difficult to move to a cluster. The program now has to give each device the right data, coordinate changes to shared parameters, and decide when calculations on different devices need to exchange results. These decisions get harder when training involves several losses or when some machines collect experience while others learn from it. TF-Replicator is an abstraction over TensorFlow for distributed [machine learning](https://md.research.elamur.ai/free/en/concepts/machine-learning/). It lets the researcher describe the work of a replica and choose how to deploy it, while keeping control of the steps that make up training and the loop that runs them.

A replica is a unit of computation that runs on a portion of the input. Its definition has an input function and a step function. The input function prepares the data, and the step function describes what to do with it. A Replicator places copies of this computation on the selected hardware and supplies the corresponding rules for moving data and updating parameters. Synchronous training can combine gradients before an update. An asynchronous implementation lets workers update parameters held on shared servers. A replica can also span several devices, so the same interface can express both dividing a batch across replicas and dividing the computation within each replica.

The authors test the design on ImageNet classification, class-conditional ImageNet image generation, and reinforcement learning from pixels. For classification, a ResNetv1-50 trained for 90 epochs on 32x TPUv2 in 28 minutes and reached 75.62% Top-1 accuracy. The single-GPU run took 7118 minutes and reached 76.19%. For image generation, increasing the SN-GAN batch size from 64 to 512, with the learning rate left as set, raised the Inception Score by a relative ∼50%. The control experiment used D4PG on the DeepMind Control Suite and kept the total learner batch at 256. Distributing that fixed batch accelerated learning as measured by episode reward over wall-clock time.

The case studies exercise different parts of the interface. The classifier needs synchronized gradient updates, the generator and discriminator require separate optimization steps and can share batch statistics, and the control agent needs to learn from data arriving through a replay service. Together they show how much of the training program can carry over as hardware and workload change. The authors also announced plans to release the TF-Replicator programming model as part of TensorFlow 2.0.

## Deep dive: TF-Replicator: Distributed Machine Learning for Researchers

TF-Replicator lets researchers move TensorFlow training across GPUs and TPUs while keeping control of their computation and training loop. · about 34 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### What changes when training leaves a single device

A researcher can ordinarily describe a training run in terms of the data to read, the calculation to perform, and the updates to make. Moving the calculation onto several devices introduces a second set of decisions. Someone has to specify where each operation runs, how input batches are divided, and how the devices agree on what parameter values to use. In a program with more than one loss, the order of calculations and updates also matters. A distribution interface has to handle these concerns while leaving the researcher enough control to express the training algorithm.

The paper motivates the problem with the rate at which the largest training runs had grown. It cites an analysis that found a compute doubling period of 3.5 months for those runs since 2012, against the historical 18 months associated with Moore’s Law. GPUs and tensor processing units, or TPUs, improve the amount of work a machine can do. The authors argue that experiments at the scale they are discussing still require increasing the number of machines. This makes [GPU and parallel computing](https://md.research.elamur.ai/free/en/topics/gpu-parallel-computing/) part of everyday experimental design for the researchers the framework was built to serve.

Distribution can mean several different things for the same training program. In data parallelism, each device can carry out the same calculation on a different portion of a batch. In model parallelism, different devices can perform different parts of a single calculation, for instance because the computation and its parameters require more memory than one device can provide. Reinforcement learning adds another distinction. Collecting experiences from simulated environments and learning from those experiences are different jobs. They can run alongside one another, and their useful degrees of parallelism can differ. These variations give researchers practical reasons to want a shared interface without making every job obey the same training procedure.

#### What TensorFlow already provided

A TensorFlow graph describes operations and the tensors that pass between them. Tensors are arrays that can have several dimensions. An operation consumes tensors or produces them, and requesting a result can trigger execution of the operations on which it depends. In a distributed graph an operation can be assigned to a specific device. This makes it possible to put computation near the data it uses, or to arrange for an operation on one machine to consume a result from another. The paper builds directly on the system described in [TensorFlow](https://md.research.elamur.ai/free/en/papers/abadi-2016-tensorflow-system-large-scale-machine/).

TensorFlow already has machinery for scheduling distributed work. The client builds the graph. A master service coordinates the execution of the relevant subgraphs, and workers run those subgraphs on their local devices. A device string identifies an operation’s intended location. The cluster specification relates logical locations to machines, and TensorFlow inserts operations that transfer tensors when their producer and consumer live on different devices. Communication within a machine and communication across a network can use different mechanisms. Thus the work of getting a tensor to its consumer is already supported. The user still has to arrange the computation and its state so that the right communication takes place.

One important responsibility is sharing variables correctly. If separate clients create resources with the same name on the same device, they can refer to the same underlying resource. That allows several workers to operate on variables stored on a parameter server. It also means a mistake in the construction or placement of a resource can change the behavior of a program quietly. Another arrangement is to construct a single large graph with several copies of the computation and let one client request a step across all of them. That makes synchronous execution natural, but it leaves the author of the graph responsible for wiring up the copies.

The authors point to TPU programming as another source of complexity. To use a TPU efficiently, a TensorFlow program has to follow the hardware’s replication pattern and manage the movement of data into and out of the computation. The low-level interface exposes this through infeed and outfeed queues. Together with state placement on a cluster, this makes switching hardware a change to the program’s organization as well as a change to its device names. The accelerator context comes from the work on the [Tensor Processing Unit](https://md.research.elamur.ai/free/en/papers/jouppi-2017-datacenter-performance-analysis-tensor-processing/).

#### The alternatives researchers had

Earlier distributed machine learning systems drew on MapReduce. The paper describes it as a way to spread keyed data processing across many machines and combine results by key. Mahout and MLI brought that style of processing to machine learning. Iterative neural network training places a different demand on the system. Many steps require the current parameter values and produce updates that matter immediately for subsequent steps. Repeatedly distributing weights and collecting updates therefore puts communication in the middle of the training loop. The authors cite SparkNet as an illustration of this cost even when intermediate data can be retained in memory.

Parameter servers give the workers a place to read or update persistent weights across steps. Workers carry out the calculations, while the servers store the parameters, potentially divided across machines. The paper traces this arrangement through systems including DistBelief, GeePS, and Project Adam. It also points to a framework that represents worker computation using dataflow graphs, [MXNet](https://md.research.elamur.ai/free/en/papers/chen-2015-mxnet-flexible-efficient-machine-learning/). TF-Replicator keeps the parameter server arrangement as one deployment choice, which matters because an asynchronous worker can update shared state without waiting for a synchronized group of replicas.

A researcher could already reach some common patterns through higher-level TensorFlow features. A replica device setter and a synchronized optimizer supported synchronous stochastic gradient descent with parameter servers. Horovod supplied another route to synchronous data parallelism. It ran separate TensorFlow graphs and used collective communication to combine their gradients. The authors describe this as a good fit for the common case of replicas doing equivalent work. A different convenience interface, TensorFlow Estimator, made some programs portable across devices but constrained how the researcher could express the run loop. [Horovod](https://md.research.elamur.ai/free/en/papers/sergeev-2018-horovod-fast-easy-distributed-deep/)

The paper gives concrete reasons why that flexibility matters. A generative adversarial network has a generator and a discriminator, with an optimization problem for each. The training loop may alternate their updates. Actor-critic reinforcement learning likewise has a policy to improve and a critic to train, and the program may need to combine these updates with work happening elsewhere in the system. The authors situate these examples alongside work on multiple losses, including synthetic gradients and [FeUdal Networks](https://md.research.elamur.ai/free/en/papers/vezhnevets-2017-feudal-networks-hierarchical-reinforcement-learning/). The extent of the difficulty depends on the algorithm. A single common optimizer can be wrapped easily, while a system whose replicas have different responsibilities requires decisions about what gets replicated in the first place. The adversarial example draws on [Generative Adversarial Nets](https://md.research.elamur.ai/free/en/papers/goodfellow-2014-generative-adversarial-nets/).

Other contemporary frameworks gave users different ways to express distribution. Mesh-TensorFlow introduced a language in which the user could map parts of the computation onto a mesh of devices. Ray addressed the combination of simulation, training, and serving in distributed reinforcement learning. The TF-Replicator authors set a particular goal within this field. They wanted existing TensorFlow research code to carry over from a single machine to a distributed setting, with hardware topology handled below the level at which most researchers define a training step. The paper treats explicit mapping as a different way to control placement, exemplified by [Mesh-TensorFlow](https://md.research.elamur.ai/free/en/papers/shazeer-2018-mesh-tensorflow-deep-learning-supercomputers/).

### The method, step by step

#### Describe one replica and its input

The unit the researcher describes is a replica. Think of a classifier that receives a batch of images, computes a loss, and uses the loss to update the classifier’s parameters. The replica describes that calculation for the images assigned to it. Another replica can run the same calculation on a different portion of the batch. The definition can also be more involved. A learner replica can take a batch of sampled trajectories and use it to carry out updates for both a policy and a critic. In either case, the work inside the replica is ordinary TensorFlow computation.

The researcher supplies an input function, `input_fn`, and a step function, `step_fn`. The input function describes how to obtain the data for a step. It can return a TensorFlow `Dataset`, or it can return a callable that supplies tensors. Those tensors can be organized in a nested structure, which allows the input to carry whatever distinct pieces the step needs. In the control example, the callable provides a batch sampled from replay. This lets the learner use the same interface for experience collected by other processes that a classifier uses for data from a dataset pipeline.

There are two ways to replicate this input pipeline. With `PER_WORKER`, one input function is instantiated on a worker, and the input it produces is split among the replicas on that worker. The split ordinarily occurs along the leading dimension of the tensors, the dimension normally used to index examples within a batch. A researcher can provide a different splitting function. The paper gives the example of a recurrent computation with time-major data, where the time dimension comes first. Dividing along that dimension would distribute slices of time, while the intended operation may be to give each replica different sequences from the same batch. With `PER_REPLICA`, each replica maintains a separate input pipeline.

The step function consumes the tensors provided by the input function and builds the operations for a step. It can return a nested collection of tensors, for example separate loss values. Its execution is placed on an accelerator, or on several devices when configured as a model-parallel replica. The distinction between building and executing the step is important. The Python function constructs the data dependencies. The resulting operations run when the training program requests the appropriate output. An example in the paper uses control dependencies to make the reported actor and critic losses depend on the execution of both optimizer updates.

Defining and running a TF-Replicator training step The steps in order.

The deployment object is created for the chosen backend and device arrangement. The program constructs its TensorFlow resources, including the trainable state and the optimizer’s computations, within the Replicator’s context. It can then ask the Replicator to build the step and return the outputs for the replicas. The example with a classifier averages the loss outputs to obtain a tensor that can be fetched in the training loop. The program initializes the Replicator in the session, runs training for the desired steps, and shuts it down through the same interface. The averaging of the reported losses and the averaging of the gradients are distinct operations. One gives the caller a step result to use or record. The other determines how the optimizer changes the parameters.

#### Choose where the replicas run

The authors provide a single-device `NonReplicator` for the case in which there is no replicated work. For synchronous execution on GPUs in one machine there is `MultiGpuReplicator`. `MultiWorkerReplicator` extends synchronous execution to several machines, each able to use its available devices. `TpuReplicator` covers TPU deployment, up to a TPU Pod in the paper’s description. A worker in this TPU terminology corresponds to a separate TPU device with a host, and one such TPU v2 has 8 cores across 4 chips. A GPU worker can be a server with several GPUs. Counting workers and counting the devices used for replica computation therefore describe different parts of the deployment.

These synchronous backends use in-graph replication. One client coordinates execution, and the graph describes work across the devices. To understand the benefit of this organization, consider a gradient computed by each replica. The graph can establish dependencies among the computations that produce those gradients and the operations that combine them. The step can then apply the update with the combined result. The client has a graph that represents the whole synchronous step, including dependencies between copies of the replica.

`MultiWorkerAsyncReplicator` uses between-graph replication. Each worker builds the graph for its local replica and uses variables on shared parameter servers. Workers can update the shared state as their work completes. Correct resource placement and matching names make separate worker graphs refer to the same stored variables. The backend in the paper assigns one device per worker. Its mechanism for sharing updates comes from parameter-server placement, which also explains why it exposes a narrower set of communication capabilities than the synchronous backends.

The paper identifies two engineering considerations that favor separate graphs. With independent worker execution, other workers can continue after a worker fails. Each client also avoids building the large replicated graph that a synchronous master would otherwise hold. The latter can matter because the paper gives 2GB as the size limit for a TensorFlow graph serialized as a protocol buffer. These considerations apply to the organization of the workers. The state on which they all depend still resides on the parameter servers, and the paper describes the benefit in terms of worker failure.

#### Aggregate gradients or exchange application data

A synchronous update has to bring together the work done on different parts of a batch. The optimizer wrapper does this before delegating the update to the base optimizer. For each gradient, it divides the local result by the number of replicas and computes an `all_sum`. The operation makes the sum available to the participating replicas. Using subscripts to express the wrapper’s calculation gives the following gradient average.

```
ḡᵥ = Σᵣ (gᵣ,ᵥ / R)
```

Here v denotes a trainable variable and r indexes a replica. The symbol gᵣ,ᵥ is the gradient for v as calculated by r, R is the number of replicas, and ḡᵥ is the averaged gradient passed to the optimizer for v. The sum Σᵣ runs over all replicas, and `/` denotes division by R. The wrapper labels each gradient collective so that the graph associates values belonging to the same reduction. The optimizer receives the resulting gradient together with the variable to which it applies.

Because each replica contributes with the same weight, the averaging rule is directly suited to evenly divided batches. Thinking through what it averages also clarifies an implementation detail in the classification experiment. A learning-rate setting suitable for an optimizer that sees a sum can have a different effect when the optimizer sees a mean. The paper therefore distinguishes its learning-rate convention from the convention used in the Cloud TPU example.

Gradient reduction is a common use of communication between replicas. The interface also exposes `all_reduce`, `all_sum`, and `all_gather`, plus broadcast, `map_reduce`, and `map_gather`. These allow the step function to express exchanges driven by the application itself. A reduction combines contributions. A gather makes contributions available together. Broadcast distributes a value. Their usefulness depends on where they occur in the calculation. For instance, if normalization in a layer uses statistics from the full batch, the replica needs to receive the combined statistics while it is still computing the forward pass.

The cross-replica batch normalization sketch first computes a local average and a local average of squared activations, then pools each quantity with `all_sum`. Its statistical part can be written as follows.

```
(m, s) = (Σᵣ (mean(hᵣ) / R), Σᵣ (mean(hᵣ²) / R))
```

Here hᵣ denotes the activations on replica r, and hᵣ² is their elementwise square. The function `mean` denotes the local TensorFlow mean in the example. The symbol R again counts replicas, Σᵣ sums over them, and division by R weights their means equally. The pair on the left contains m, the pooled mean, and s, the pooled mean of the squares. For local statistics summarizing equally sized portions of the batch, these reductions pool information across the full batch.

The final line of the example prints the following expression.

```
(h − m) / √(s − m)
```

In this line h is the activation being normalized, m and s are the pooled statistics just defined, `−` is subtraction, and `√` takes the square root of its argument. There is a discrepancy in the sketch. A variance computed from a second moment subtracts the square of the mean. The printed denominator subtracts the mean itself. The example establishes how to use `all_sum` to share the moments. It leaves the exact normalization used in the reported benchmark uncertain.

#### Split the work inside a replica when needed

Data parallelism gives different inputs to copies of a computation. Model parallelism divides the computation itself among devices. The paper motivates the latter with networks whose working state is large, including the historical example of [AlexNet](https://md.research.elamur.ai/free/en/papers/krizhevsky-2012-imagenet-classification-deep-convolutional/). TF-Replicator lets the researcher describe placement inside a replica by asking for a logical device. This identifier denotes a location relative to that replica. The deployment resolves it to a physical device in the cluster.

The paper illustrates the combination with 8 GPUs and 2 devices per replica. This yields the example’s 4 data-parallel replicas, each with a computation placed across its own pair of devices. To describe where an operation belongs, the step function can name the same logical device in each replica. The Replicator chooses the corresponding physical device for that copy. This preserves two different kinds of data movement. Operations within a replica can consume tensors produced elsewhere in that replica, while replicas can still exchange results through a collective whenever the algorithm calls for it.

#### Resolve communication when the graph is built

There is a practical problem underneath the apparently simple `all_sum` call. A researcher can put the call in the middle of a step function. When TensorFlow is constructing the first replica’s graph, the other replica graphs may still be missing. The continuation of the first replica needs a tensor to stand for the collective result, but the inputs to that result include tensors whose operations have yet to be defined. If collectives were restricted to a point after all replica outputs had been built, the interface could easily connect them there. That restriction would rule out an exchange such as the batch statistics needed partway through a forward calculation.

For `MultiGpuReplicator` and `MultiWorkerReplicator`, the authors solve this with temporary operations. The graph builder records a placeholder at the point where a replica requests the shared result. It can then build the rest of the replica using that placeholder. Once all replica subgraphs exist, TF-Replicator rewrites the placeholders so that the graph connects the actual participants in the collective. The operations consuming the result now depend on the appropriate cross-replica computation. This happens when constructing the graph. Each executed step uses the dependencies that construction established.

The paper describes a different way to address construction order in TensorFlow’s DistributionStrategy. Separate Python threads can build the replicas and wait at a barrier when a collective needs to be connected. The authors chose the placeholder approach so that replica definitions could be constructed independently without managing TensorFlow’s thread-safety requirements in this part of the implementation. They provide this as a design explanation. The performance studies benchmark training workloads and do not time the construction alternatives against each other.

The TPU path also uses in-graph replication, with the cross-replica operations implemented through XLA, the Accelerated Linear Algebra compiler. The paper gives TPU cross-replica sum as the example. On the asynchronous path, gradient accumulation takes place through variables on shared parameter servers. That path has no equivalent support for the other collectives in the paper’s implementation. A step whose forward pass needs globally pooled statistics therefore has a deployment requirement beyond its need to share trainable parameters.

#### Apply the interface to a classifier and a generator

For ImageNet classification the paper uses a ResNetv1-50 corresponding to the architecture in the Cloud TPU benchmark. Residual networks use skip connections, which pass information across layers as well as through the intervening operations. The classifier case in TF-Replicator is a synchronous training problem. Each device receives images, computes the classifier’s contribution to the update, and participates in gradient aggregation. The `PER_WORKER` input pipeline splits the worker’s input among the replicas. The underlying architecture comes from [Deep Residual Learning for Image Recognition](https://md.research.elamur.ai/free/en/papers/he-2015-deep-residual-learning-image-recognition/).

The standard local batch is 64 images per GPU or TPU core. For the largest configuration, 32x TPUv2, the local batch is 32 images per core. The optimizer uses Nesterov momentum, and the learning rate increases linearly over 6 epochs. The paper states the maximum using the batch size.

```
ηₘₐₓ = B / 2048
```

Here ηₘₐₓ is the maximum learning rate after warmup, B denotes the batch size in the schedule, and `/` denotes division by the constant 2048. The paper then specifies a 90% learning-rate decay at epochs 30, 60 and 80. Its optimizer consumes an average of replica gradients. The authors cite that choice when explaining the different learning-rate convention from the TPUEstimator example, which sums the gradients.

The generative task changes what a step has to express. The generator produces an image from a random input. The discriminator judges whether an input image came from the data or the generator. The objective provides an incentive for the discriminator to distinguish the two sources, and the generator improves by producing samples that are harder to distinguish. The paper introduces this setup through the vanilla GAN objective before describing its class-conditional SN-GAN experiment.

```
V(G, D) = 𝔼ₓ∼qdata(x)[log D(x)] + 𝔼_z∼p(z)[log(1 − D(G(z)))]
```

Here V is the GAN value, G is the generator, and D is the discriminator. The variable x is a real sample drawn from the data distribution qdata, and z is a random input drawn from p. The notation `∼` indicates that a variable is drawn from the named distribution, and 𝔼 denotes an expectation under that distribution. D(x) is the discriminator’s estimate that the real sample x came from the data. G(z) is the generated sample, and D(G(z)) is the discriminator’s estimate that it is real. The expression `1 − D(G(z))` is the complementary estimate. The logarithm is written `log`, and the plus sign combines the expectations for real and generated samples. The paper names a common choice for the input distribution.

```
z ∼ 𝒩(0, I)
```

Here 𝒩 denotes a normal distribution, 0 is its zero mean, and I is the identity covariance matrix. As before, z is a draw from the indicated distribution. The equation describes the input to the illustrative vanilla generator. The paper’s experimental description adds class information and uses spectral normalization in the discriminator.

The generator and discriminator are trained with alternating updates. The authors describe earlier GAN work as tackling the difficulty of training through changes to the objective and through changes to the conditioning of the networks. Spectral normalization rescales discriminator parameters using their largest singular values, which the paper connects to controlling how sensitively the discriminator responds to its input. For the benchmark, the authors use the hyper-parameters of Zhang and colleagues and give the generator class information through class-conditional batch normalization. The discriminator uses [projection discrimination](https://md.research.elamur.ai/free/en/papers/miyato-2018-cgans-projection-discriminator/).

The replication interface supplies two ingredients for the experiment. It gives the authors a way to preserve generator and discriminator optimization as separate calculations, and it lets the computation exchange batch statistics through `all_sum`. The former matters because the program determines which update to execute. The latter matters because each replica sees only its own portion of the batch until the statistics have been shared. The exchanges implement a training choice within SN-GAN. The larger batch and the cross-replica normalization are distinct choices even when they are used in the same run.

#### Separate the control agent’s experience collection from learning

In the reinforcement learning case, the data arrive through interaction. At a step indexed by time, the agent sees an observation, chooses an action, and receives a reward. Its policy maps observations to actions. The action-value function represents the expected discounted return when a specified action is taken first and the policy controls later actions. Discounting gives future rewards a weight that depends on how far in the future they occur. The paper expresses the action value as follows.

```
Qᵖⁱ(x, a) = 𝔼[Σₜ₌₀^∞ γᵗ r(xₜ, aₜ)]
```

Here `Qᵖⁱ` denotes the value function for policy π. The variables x and a specify the initial observation and action, so x₀ is x and a₀ is a. The index t denotes time, xₜ and aₜ are the observation and action at that time, and r(xₜ, aₜ) is the reward. The factor γ is the discount, and γᵗ weights the reward according to its time index. The sum runs from the initial time 0 over the future, indicated by ∞. The expectation 𝔼 averages over trajectories with that starting observation and action and with subsequent behavior governed by the policy.

```
xₜ ∼ p(· | xₜ₋₁, aₜ₋₁)
```

Here p is the environment’s transition distribution. The dot stands for the possible next observation, `|` denotes conditioning, and xₜ₋₁ and aₜ₋₁ are the previous observation and action. The symbol `∼` means that xₜ is sampled from that distribution. After the initial action, the deterministic policy supplies the action at each subsequent observation.

```
aₜ = π(xₜ)
```

Here π is the policy, which returns action aₜ for observation xₜ. In discrete action spaces a policy can choose the action with the largest estimated value. For continuous control the paper describes a parameterized policy that proposes the action directly. This is the actor’s role in the deterministic policy gradient approach discussed in [Continuous control with deep reinforcement learning](https://md.research.elamur.ai/free/en/papers/lillicrap-2015-continuous-control-deep-reinforcement-learning/).

```
J(θ) = 𝔼[Qᵖⁱᶿ(x, πθ(x))]
```

Here J is the objective for the actor’s policy parameters θ. The expression πθ(x) is the action proposed by the policy with parameters θ at observation x. The notation `Qᵖⁱᶿ` means the action-value function for that policy. The expectation 𝔼 averages the value assigned to the proposed action over observations. The paper then writes the approximate gradient used in deterministic policy gradient learning.

```
∇θ J(θ) ≈ 𝔼ρ[∇θ πθ(x) ∇ₐ Qw(x, a)] evaluated at a = πθ(x)
```

Here ∇θ denotes differentiation with respect to the actor parameters θ and ∇ₐ denotes differentiation with respect to the action a. The critic, Qw, is a network with parameters w. It approximates the action-value function and supplies the sensitivity of value to the actor’s proposed action. The factor ∇θ πθ(x) gives the sensitivity of that action to the actor parameters. Their product uses the critic’s action derivative to indicate how changing the actor would affect the estimated value. The expectation 𝔼ρ averages over the state-visitation distribution ρ, and `≈` indicates that this is an approximation to the objective gradient. The action derivative is evaluated at the action actually proposed by the deterministic policy.

The observations used for learning can come from a policy that explores. That gives the distributed system a way to decouple acting from learning. The paper implements the D4PG learner, an off-policy actor-critic algorithm that includes a distributional Bellman operator. Separate actor processes interact with their own instances of the environment, following an exploration policy and writing transitions into replay. A transition records an experience that the learner can later sample. The distinction between the behavior used to collect experience and the policy being optimized allows a replayed transition to remain useful after the parameters change.

In this implementation the replay store lives outside the TensorFlow graph. The authors describe it as a memcached-style key-value store. Sampler processes draw batches from it and make them accessible through a callable for `input_fn`. The learner uses TF-Replicator to divide the sampled batch across devices. Each step computes the losses needed for the actor and critic and runs the corresponding updates. Actors periodically request parameters from the learner through remote procedure calls. This keeps their exploration centered on the policy represented by recent parameter values while allowing experience collection and training to proceed concurrently.

The control experiments use 84x84 RGB images from each task’s default camera. The learner receives a stack of n = 3 frames so the representation can carry information about movement between observations. A shared 9-layer ResNet turns those stacked frames into a length-64 embedding, which serves as input to both the actor and critic. The actor and critic use the architectures from the D4PG work. The paper allocates 32 actor processes and 8 sampler processes per learner replica, with the stated goal of roughly preserving the ratio of acting to learning and avoiding excessive reuse of stale data. The remaining hyper-parameters follow the D4PG work.

#### The related-work notation

The paper also gives a symbolic description of MapReduce to explain the historical distinction between batch dataflow and repeated training updates. Its map operation has the following form.

```
map(k₁, v₁) → list[k₂, v₂]
```

Here k₁ is an input key and v₁ its associated value. Each k₂ and v₂ denotes a key and value emitted by the mapping operation. The arrow indicates the returned result, and `list[k₂, v₂]` denotes a collection of output key-value pairs. The reduce operation processes the values grouped under a common output key.

```
reduce(k₂, list[v₂]) → list[v₂]
```

Here k₂ is the key for a group, `list[v₂]` on the left holds the values associated with that key, and `list[v₂]` on the right denotes the resulting list in the paper’s notation. The arrow again marks the return value. For a parameter server, the paper uses `push(k,v)` and `pull(k)` to describe operations on shared state. The key k identifies the relevant stored item, and v is the value supplied with a push. Pull requests the value by key. These signatures describe the earlier systems that motivate the discussion. TF-Replicator uses TensorFlow graphs and, when configured for asynchronous learning, relies on its shared variables for the corresponding parameter-server arrangement.

### Experiments and results

#### ImageNet classification across GPUs and TPUs

The classification experiment asks how quickly a standard ResNetv1-50 can complete training on ImageNet using TF-Replicator. The curve figure follows log loss, Top-1 accuracy, and Top-5 accuracy. Log loss reflects the probabilities the classifier assigns to the correct labels. Top-1 asks whether the correct label received the highest score, and Top-5 asks whether it was among the highest-ranked guesses permitted by that metric. The numerical table pairs final Top-1 accuracy with total time after 90 epochs. Thus each timing measures a run of the same stated duration in epochs. It is separate from the question of when a curve first passes a particular accuracy.

The paper uses the term weak scaling for increasing the amount of work alongside the available computation. In this experiment, local batches ordinarily contain 64 images, and adding accelerators increases the amount of data processed by a synchronized step. The 32x TPUv2 configuration is the exception with 32 images for each core. The training program uses the same input and step definitions when moving between the cited GPU and TPU implementations. The selected Replicator changes, with `MultiGpuReplicator` covering the single-machine GPU runs, `MultiWorkerReplicator` the larger GPU deployments, and `TpuReplicator` the TPU runs.

On the GPU side, the single-GPU run takes 7118 minutes. The 8x GPU run takes 1049 minutes. With 32x GPU arranged as 4x8 the reported time is 330 minutes, and the 64x GPU run arranged as 8x8 takes 182 minutes. The grouping indicates how the devices are distributed among workers. On the TPU side, the times are 188 minutes for 4x TPUv2, 47 minutes for 16x TPUv2, and 28 minutes for 32x TPUv2. These are all times for the ImageNet classification run through the stated 90 epochs.

ImageNet ResNetv1-50 training time through 90 epochs by device configuration The largest TPU configuration completes the reported training schedule fastest.

**The numbers**

| System or setting | minutes |
| --- | --- |
| 1x GPU | 7118 |
| 8x GPU | 1049 |
| 32x GPU (4x8) | 330 |
| 64x GPU (8x8) | 182 |
| 4x TPUv2 | 188 |
| 16x TPUv2 | 47 |
| 32x TPUv2 (this paper) | 28 |

The matching GPU Top-1 accuracies are 76.19% for 1x GPU, 76.14% for 8x GPU, 76.46% for 32x GPU, and 76.14% for 64x GPU. The TPU runs reach 76.34% for 4x TPUv2, 75.64% for 16x TPUv2, and 75.62% for 32x TPUv2. These final measurements give a way to judge what the timing chart alone would leave open. The fastest configuration reaches the published ResNetv1-50 reference accuracy of 75.3% at the end of the schedule, while the highest reported final accuracy among the runs comes from the 32x GPU configuration. The reference value is an accuracy baseline drawn from earlier published work. The table’s TF-Replicator numbers are reported as final ImageNet Top-1 results without a split designation in that table.

Final ImageNet Top-1 accuracy for ResNetv1-50 by device configuration All of the reported configurations clear the published reference accuracy, with the highest final value on the multi-worker GPU run marked below.

**The numbers**

| System or setting | Top-1 accuracy % |
| --- | --- |
| Published ResNetv1-50 reference | 75.3 |
| 1x GPU | 76.19 |
| 8x GPU | 76.14 |
| 32x GPU (4x8) (this paper) | 76.46 |
| 64x GPU (8x8) | 76.14 |
| 4x TPUv2 | 76.34 |
| 16x TPUv2 | 75.64 |
| 32x TPUv2 | 75.62 |

The paper places the work in an established line of ImageNet benchmarking. Its account follows AlexNet with architectures including GoogLeNet and [VGG](https://md.research.elamur.ai/free/en/papers/simonyan-2014-very-deep-convolutional-networks-large/), then turns to studies that reduced the time needed to reach an accuracy target. It gives ∼75% Top-1 accuracy as a typical target for those studies. Goyal and colleagues trained ResNet-50 in 1 hour with a batch size of 8K on 256 GPUs. Akiba and colleagues are cited in the discussion of 15 minutes, using a 32K batch with 1024 Tesla P100s. These are published comparison points from experiments with their own hardware and training choices. [Accurate, Large Minibatch SGD](https://md.research.elamur.ai/free/en/papers/goyal-2017-accurate-large-minibatch-sgd-training/) · [Extremely Large Minibatch SGD](https://md.research.elamur.ai/free/en/papers/akiba-2017-extremely-large-minibatch-sgd-training/)

The paper also discusses ring-based all-reduce in this literature, where the organization of the exchange among devices is itself an object of optimization. It cites the 6.6 minutes obtained with 2048 Tesla P40 GPUs in the work of Jia and colleagues. This helps explain the authors’ use of competitive performance. Their central measurement is what a researcher can obtain using a shared implementation without systems optimization tailored to image classification. The comparison with prior results therefore provides a scale for interpreting the outcome, while the synchronized training runs provide the direct evidence for TF-Replicator. [Highly Scalable Deep Learning Training System with Mixed-Precision](https://md.research.elamur.ai/free/en/papers/jia-2018-highly-scalable-deep-learning-training/)

#### ImageNet sample quality for class-conditional SN-GAN

In the generative experiment, the system learns to produce images in specified ImageNet classes. The samples in the evaluation are 128x128. The authors describe the default hardware for the comparison in the figure as 8 NVIDIA Tesla V100 GPUs, with other configurations identified separately. The training approach is again weak scaling, since the available devices let the authors use a larger batch than would fit on a single GPU. Here the main outcome is generated sample quality. Elapsed training time, which organizes much of the classifier comparison, is secondary to that question.

The paper reports Inception Score and Fréchet Inception Distance, abbreviated FID. These provide two views of sample quality. A higher Inception Score is favorable. FID is a distance comparing generated images with real data in a feature representation, so a smaller value is favorable. The authors put the numerical measures alongside example images in the figure. The motivation for this comparison is whether the larger batches enabled by the distribution interface help produce better samples. The Inception Score is associated with [Improved Techniques for Training GANs](https://md.research.elamur.ai/free/en/papers/salimans-2016-improved-techniques-training-gans/).

The clearest numerical comparison in the discussion is the change from batch size 64, which the authors associate with the earlier projection-discriminator setup, to 512. They report a relative improvement of ∼50% in Inception Score and state that they did not adapt the learning rate for that change. The batch sizes describe the training inputs. The percentage describes the score change. The comparison is about the resulting ImageNet samples, and the relative change is the paper’s reported quantity. The authors also attribute a further 5-10% performance boost to cross-replica batch normalization. They do not identify a specific metric for that percentage in the sentence reporting it, so the percentage cannot be read as a numerical change in either named metric individually.

The practical role of the extra devices is to make the larger batch feasible and provide the collectives needed if normalization is performed across replicas. GPU and TPU deployments are both part of the experiment. The paper refers to the figure for the associated score and distance comparisons, and its discussion gives the relative Inception Score gain as the main quantitative statement. In this workload the immediate result is that a researcher can use the same distribution interface to change the batch and the scope of normalization while retaining the alternating generator and discriminator computation.

#### DeepMind Control Suite learning from pixels

In the control benchmark, a fixed dataset would miss an important part of training. The data are produced by the actors as they interact with the tasks. The learner samples their experiences, and updated policy parameters guide later interaction. The evaluation uses tasks from the DeepMind Control Suite, described by the authors as a range of physically realistic control problems. The learner works from stacked camera images. The relevant earlier D4PG experiments, as described by the paper, used low-dimensional observations such as positions and velocities. The benchmark here therefore assesses a D4PG implementation with a visual input pipeline and a different arrangement for replay.

The total learner batch is fixed at 256, the largest the authors could fit on a single GPU in this setup. This is the paper’s strong-scaling experiment. Additional devices take a smaller portion of a batch of the same total size. The figure compares a single V100 GPU, a TPUv2 chip with 2 cores, 8x NVIDIA Tesla V100 GPUs, and a full TPUv2 device with 4 chips and 8 cores. The hardware comparison therefore includes a smaller and a larger configuration within TPUv2 as well as the GPU deployments.

Reward is plotted against wall-clock time. The paper describes the plotted performance in its discussion as mean episode reward. In the figure caption it refers to total environment reward for the control tasks. The reported result is that distributing the fixed-size learner batch substantially accelerates learning, and the full TPUv2 device is competitive with the 8 NVLink-connected Tesla V100 GPUs in this setting. The paper’s discussion describes the curves instead of giving a reward value at a stated time. This evidence concerns how quickly the agent accumulates reward as training proceeds under each deployment, with the total learner batch held to the same size.

The three case studies consequently use different outcomes to evaluate distribution. The classifier reports time together with final accuracy. The GAN experiment asks whether the larger batch produces higher-quality samples. The control experiment uses reward over elapsed time under a fixed batch. A single throughput number would leave these questions unresolved. Training more quickly, improving generated samples, and learning a control task sooner are distinct experimental outcomes even though the programs share a replication interface.

### What the ablations show

The paper has no comprehensive component ablation. Its closest controlled comparisons vary classifier hardware and batch allocation, GAN batch size and normalization, and control hardware while holding the learner batch fixed. These comparisons answer questions about when the framework makes a particular training arrangement practical. They give less direct evidence about the isolated performance cost or benefit of any one part of the framework.

#### More devices in the classifier

For the classifier, the architecture, length of training, and broad optimizer procedure are shared across the deployments. The comparison shows that the authors can use the standard TF-Replicator implementation at several scales and produce final ImageNet accuracies near the published reference while changing time substantially. There is useful evidence within the GPU family because the results include both single-worker and multi-worker arrangements. The TPU configurations show the same broad pattern of declining time as the deployment grows. The final accuracy chart also makes clear that an ordering by speed gives a different ordering from one based on accuracy.

Several quantities change together. Increasing the number of accelerators usually increases the total batch. The peak learning rate depends on the batch size, and the largest TPU configuration changes the size of the batch on each core. Differences in the final results can consequently reflect optimization as well as hardware. The comparison evaluates complete training configurations. It has no matched run in which the same synchronized computation and hardware are executed with and without the replication interface. It also leaves the contributions of the collective implementation and the input pipeline unmeasured individually.

#### Batch size and shared statistics in the GAN

The GAN offers a more direct comparison of a training setting. The authors report the score improvement from increasing the batch with the learning rate carried over. This establishes that a change to the learning-rate schedule was unnecessary for the reported Inception Score improvement in this case. It gives evidence for the larger batch as a useful practical intervention in their SN-GAN setup. The result is especially pertinent to a replication framework, since the smaller hardware configuration limited the batch sizes the researchers could try.

The authors separately credit cross-replica batch normalization with an additional improvement. This tests the relevance of allowing communication during the forward computation. Partitioning a batch across devices means local normalization sees part of that batch. Exchanging moment statistics enlarges the set of activations that determines the normalization for each replica. The reported benefit gives a workload-level reason to expose a collective to the step function. The discussion leaves open how much of the improvement appears in each sample-quality metric and how strongly the normalization effect depends on the batch size or hardware configuration.

#### A fixed batch in the control experiment

The control comparison avoids increasing the global batch as part of the hardware change. This is important because the authors observed that larger batches could make learning worse on many of the tasks. A fixed total batch allows the benchmark to address whether devices can share the learner computation while preserving that training choice. The resulting reward curves support acceleration in the authors’ setup.

This comparison still incorporates the full actor, sampler, and learner system. Actor and sampler allocations are sized per learner replica to keep the intended balance. The complete experiment therefore varies more than the number of devices carrying out tensor operations. A benchmark aimed at isolating learner speed would need to account separately for the rate of experience collection, the rate of sampling, and the rate of learner updates. The comparison in the paper shows the outcome when these parts are used together.

### Limitations

#### Limits the authors identify

The available communication depends on the deployment. The synchronous GPU and TPU paths support collective operations used within a replica step. The asynchronous backend in the paper supports gradient accumulation through shared variables on parameter servers, with the other communication primitives unavailable there. This constrains portability for a training step that makes a direct request for a cross-replica statistic or another collective. The abstract form of the step remains valuable, but choosing a deployment still requires understanding which dependencies the computation has.

The authors also identify conditions under which a scaling strategy can be a poor fit for a workload. Large batches worked well for the image generation experiment, yet the authors observed negative effects from larger batches on many Control Suite tasks. They chose strong scaling for D4PG so they could keep the batch at 256. The batch that fit on the single GPU defined their comparison point. The paper’s accelerations should therefore be read with the scaling regime and the learning objective in view. It gives examples of successful weak and strong scaling under different conditions.

Graph size, worker failure, and TPU input handling motivate the design. The authors explain why independent workers can continue after a worker fails and why building separate graphs can ease pressure on the graph-size limit. These are consequences of the architecture they describe. The reported experiments focus on training performance. Failure recovery, serialized graph size at the largest tested deployments, and the comparative cost of graph construction do not have corresponding measurements in the case studies.

#### Limits apparent from the experimental setup

The strongest portability example is the shared classifier code across GPU and TPU realizations. The other examples show that workloads with different requirements can be represented using the same interface. That is narrower evidence than testing every workload on every backend. The model-parallel API is illustrated by a device-placement example, while the main performance results concern dividing batches among replicas. There is no model-parallel throughput or memory comparison with another distributed framework. The asynchronous backend likewise has an implementation description without a corresponding head-to-head performance study.

The classifier comparisons against published training times combine results produced under different conditions. Earlier studies used different accelerator types and counts, large-batch training procedures, and their own communication or precision choices. The paper’s timing table supplies clear evidence for the complete reported runs. Estimating a framework overhead relative to Horovod or a hand-tuned TensorFlow implementation would require matched hardware and training settings. The benchmark also gives no measure of resource cost or utilization. Wall-clock time supports conclusions about elapsed time under the stated deployment.

The GAN evidence is specific to class-conditional ImageNet generation with the stated training setup. The paper quantifies the relative Inception Score gain for the batch comparison and reports an additional performance percentage for cross-replica normalization. It does not supply a numerical breakdown of that percentage across the two metrics in the discussion. The mismatch in the printed normalization denominator also makes the sketch insufficient for recovering that part of the benchmark implementation exactly. The communication mechanism and the measured outcome remain distinct pieces of evidence.

The D4PG benchmark changes both the observation representation and the replay arrangement from the earlier D4PG work as described by the authors. It therefore demonstrates an implementation that learns from pixels, with experience served through an external store. The comparisons among its own hardware configurations are relevant to that implementation. They leave open how much of any difference from the earlier D4PG experiments would come from observation encoding, the training system, or the changed replay design. The actor and sampler configuration also means the wall-clock curves concern the whole distributed program.

Finally, ease of use is a central motivation, and the paper supports it by showing short replica definitions and a shared API across different workloads. There is no systematic measurement of how much development time researchers save or what distributed systems knowledge they need for unfamiliar cases. The examples establish that the interface can express the reported training runs. Claims about wider adoption, developer effort, and performance on other training systems would require evidence beyond these experiments.

### What came after

The concrete forward step recorded by the authors is their plan to open-source the TF-Replicator programming model as part of TensorFlow 2.0. That plan concerns the interface for defining and deploying replicated computation. The paper presents it as an announced release, and its benchmarks evaluate the implementation described in the research. Subsequent release details and follow-on studies that adopted or extended the design are undocumented in the paper’s account.

## Cite

Cite as Peter Buchlovsky, David Budden, Dominik Grewe, Chris Jones, John Aslanides, Frederic Besse, Andy Brock, Aidan Clark, Sergio Gomez Colmenarejo, Aedan Pope, Fabio Viola and Dan Belov. 2019. TF-Replicator: Distributed Machine Learning for Researchers. arXiv:1902.00465.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.48550/arxiv.1902.00465](https://doi.org/10.48550/arxiv.1902.00465) · [arXiv 1902.00465](https://arxiv.org/abs/1902.00465)

```bibtex
@misc{buchlovsky2019tf,
  title = {{TF-Replicator: Distributed Machine Learning for Researchers}},
  author = {Peter Buchlovsky, David Budden, Dominik Grewe, Chris Jones, John Aslanides, Frederic Besse, Andy Brock, Aidan Clark, Sergio Gomez Colmenarejo, Aedan Pope, Fabio Viola and Dan Belov},
  year = {2019},
  doi = {10.48550/arxiv.1902.00465},
  eprint = {1902.00465},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.1902.00465}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
