|
| 1 | +import dataclasses |
| 2 | +from abc import ABC |
| 3 | +from typing import Callable, Optional |
| 4 | + |
| 5 | +import torch |
| 6 | + |
| 7 | + |
| 8 | +class AccumulatorBase(ABC): |
| 9 | + def accumulate_part(self, tensor: torch.Tensor, weight: float) -> None: |
| 10 | + ... |
| 11 | + |
| 12 | + def reduce(self) -> torch.Tensor: |
| 13 | + ... |
| 14 | + |
| 15 | + |
| 16 | +AccumulatorFactory = Callable[[torch.Size, int], AccumulatorBase] |
| 17 | + |
| 18 | + |
| 19 | +class MeanAccumulator(AccumulatorBase): |
| 20 | + def __init__(self, part_shape: torch.Size, _n_peers: int): |
| 21 | + self._accumulator = torch.zeros(part_shape) |
| 22 | + self._denominator = 0.0 |
| 23 | + |
| 24 | + def accumulate_part(self, tensor_part: torch.Tensor, weight: float) -> None: |
| 25 | + self._accumulator.add_(tensor_part, alpha=weight) |
| 26 | + self._denominator += weight |
| 27 | + |
| 28 | + def reduce(self) -> torch.Tensor: |
| 29 | + return self._accumulator.div_(self._denominator) |
| 30 | + |
| 31 | + |
| 32 | +class CenteredClipAccumulator(AccumulatorBase): |
| 33 | + def __init__(self, part_shape: torch.Size, n_peers: int, **kwargs): |
| 34 | + self._kwargs = kwargs |
| 35 | + |
| 36 | + self._tensors = torch.empty([n_peers] + part_shape) |
| 37 | + self._weights = torch.empty(n_peers) |
| 38 | + self._index = 0 |
| 39 | + |
| 40 | + def accumulate_part(self, tensor_part: torch.Tensor, weight: float) -> None: |
| 41 | + self._tensors[self._index] = tensor_part |
| 42 | + self._weights[self._index] = weight |
| 43 | + self._index += 1 |
| 44 | + |
| 45 | + def reduce(self) -> torch.Tensor: |
| 46 | + clipped = centered_clip(self._tensors, self._weights, **self._kwargs) |
| 47 | + return clipped.result |
| 48 | + |
| 49 | + |
| 50 | +@dataclasses.dataclass(frozen=True) |
| 51 | +class CenteredClipResult: |
| 52 | + result: torch.Tensor |
| 53 | + n_clipped: torch.Tensor |
| 54 | + last_step_delta: torch.Tensor |
| 55 | + |
| 56 | + |
| 57 | +def centered_clip(input_tensors: torch.Tensor, weights: torch.Tensor, |
| 58 | + tau: float = 1.0, n_iters: int = 20, stop_delta: Optional[float] = None) -> CenteredClipResult: |
| 59 | + """ |
| 60 | + Optimized implementation of CenteredClip from [Karimireddy, 2021]. |
| 61 | + Intended to be used in a decentralized fashion as in [Gorbunov, 2021]. |
| 62 | +
|
| 63 | + :stop_delta: Stop iterations early if the ``L_inf`` norm of the last step is less than ``stop_delta``. |
| 64 | + Note: if this option is used, the step norm calculations may increase the time per iteration by ~25%. |
| 65 | +
|
| 66 | + References: |
| 67 | +
|
| 68 | + [Karimireddy, 2021] Karimireddy, Sai Praneeth, Lie He, and Martin Jaggi. "Learning from history for byzantine |
| 69 | + robust optimization." International Conference on Machine Learning. PMLR, 2021. |
| 70 | +
|
| 71 | + [Gorbunov, 2021] Gorbunov, Eduard, Alexander Borzunov, Michael Diskin, and Max Ryabinin. |
| 72 | + "Secure Distributed Training at Scale." arXiv preprint arXiv:2106.11257 (2021). |
| 73 | + """ |
| 74 | + |
| 75 | + with torch.no_grad(): |
| 76 | + n_peers = input_tensors.shape[0] |
| 77 | + result_shape = input_tensors.shape[1:] |
| 78 | + |
| 79 | + input_tensors = input_tensors.flatten(start_dim=1) |
| 80 | + weights /= weights.sum() |
| 81 | + |
| 82 | + # This finds medians faster than torch.median() and torch.quantile(q=0.5), |
| 83 | + # see https://github.com/pytorch/pytorch/issues/51450 |
| 84 | + sorted_tensors = input_tensors.sort(dim=0).values |
| 85 | + result = sorted_tensors[n_peers // 2].clone() |
| 86 | + delta = None |
| 87 | + |
| 88 | + diff = torch.sub(input_tensors, result, out=sorted_tensors) # Reuse memory from `sorted_tensors` |
| 89 | + for _ in range(n_iters): |
| 90 | + norms = diff.norm(dim=1) |
| 91 | + coeffs = weights * torch.minimum(torch.tensor(1.0), tau / norms) |
| 92 | + |
| 93 | + if stop_delta is not None: |
| 94 | + prev_diff = result[...] = diff[0] # Reuse memory from `result` |
| 95 | + |
| 96 | + # We only need to update `diff` (not `result`) between iterations |
| 97 | + diff.addmm_(-coeffs.repeat(n_peers, 1), diff) |
| 98 | + |
| 99 | + if stop_delta is not None: |
| 100 | + delta = prev_diff.sub_(diff[0]).max() |
| 101 | + if delta < stop_delta: |
| 102 | + break |
| 103 | + torch.sub(input_tensors[0], diff[0], out=result) |
| 104 | + |
| 105 | + return CenteredClipResult(result=result.reshape(result_shape), |
| 106 | + n_clipped=(tau < norms).sum(), |
| 107 | + last_step_delta=delta) |
0 commit comments