Replicates a model on different GPUs. Specifically, this function implements single-machine multi-GPU data parallelism. It works in the following way: - Divide the model's input(s) into multiple sub-batches. - Apply a model copy on each sub-batch. Every model copy is executed on a de
(model, gpus, cpu_merge=True, cpu_relocation=False)
| 35 | |
| 36 | @keras_export('keras.utils.multi_gpu_model') |
| 37 | def multi_gpu_model(model, gpus, cpu_merge=True, cpu_relocation=False): |
| 38 | """Replicates a model on different GPUs. |
| 39 | |
| 40 | Specifically, this function implements single-machine |
| 41 | multi-GPU data parallelism. It works in the following way: |
| 42 | |
| 43 | - Divide the model's input(s) into multiple sub-batches. |
| 44 | - Apply a model copy on each sub-batch. Every model copy |
| 45 | is executed on a dedicated GPU. |
| 46 | - Concatenate the results (on CPU) into one big batch. |
| 47 | |
| 48 | E.g. if your `batch_size` is 64 and you use `gpus=2`, |
| 49 | then we will divide the input into 2 sub-batches of 32 samples, |
| 50 | process each sub-batch on one GPU, then return the full |
| 51 | batch of 64 processed samples. |
| 52 | |
| 53 | This induces quasi-linear speedup on up to 8 GPUs. |
| 54 | |
| 55 | This function is only available with the TensorFlow backend |
| 56 | for the time being. |
| 57 | |
| 58 | Arguments: |
| 59 | model: A Keras model instance. To avoid OOM errors, |
| 60 | this model could have been built on CPU, for instance |
| 61 | (see usage example below). |
| 62 | gpus: Integer >= 2, number of on GPUs on which to create |
| 63 | model replicas. |
| 64 | cpu_merge: A boolean value to identify whether to force |
| 65 | merging model weights under the scope of the CPU or not. |
| 66 | cpu_relocation: A boolean value to identify whether to |
| 67 | create the model's weights under the scope of the CPU. |
| 68 | If the model is not defined under any preceding device |
| 69 | scope, you can still rescue it by activating this option. |
| 70 | |
| 71 | Returns: |
| 72 | A Keras `Model` instance which can be used just like the initial |
| 73 | `model` argument, but which distributes its workload on multiple GPUs. |
| 74 | |
| 75 | Example 1: Training models with weights merge on CPU |
| 76 | |
| 77 | ```python |
| 78 | import tensorflow as tf |
| 79 | from keras.applications import Xception |
| 80 | from keras.utils import multi_gpu_model |
| 81 | import numpy as np |
| 82 | |
| 83 | num_samples = 1000 |
| 84 | height = 224 |
| 85 | width = 224 |
| 86 | num_classes = 1000 |
| 87 | |
| 88 | # Instantiate the base model (or "template" model). |
| 89 | # We recommend doing this with under a CPU device scope, |
| 90 | # so that the model's weights are hosted on CPU memory. |
| 91 | # Otherwise they may end up hosted on a GPU, which would |
| 92 | # complicate weight sharing. |
| 93 | with tf.device('/cpu:0'): |
| 94 | model = Xception(weights=None, |
nothing calls this directly
no test coverage detected