Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion deepspeed/checkpoint/zero_affine.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,9 @@ def _global_ranks(group):

def _check_zero3_param_storage(param):
from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum
from deepspeed.runtime.zero.utils import is_quantized_partition

if hasattr(param.ds_tensor, 'ds_quant_scale'):
if is_quantized_partition(param.ds_tensor):
raise NotImplementedError('Quantized ZeRO-3 parameter storage has no affine storage map.')
# NVMe offload swaps a partition out of memory and leaves a placeholder in its place.
if getattr(param.ds_tensor, 'final_location', None) == OffloadDeviceEnum.nvme:
Expand Down
38 changes: 32 additions & 6 deletions deepspeed/runtime/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@
from deepspeed.runtime.zero.stage_1_and_2 import DeepSpeedZeroOptimizer
from deepspeed.runtime.zenflow.zenflow_stage_1_and_2 import ZenFlowZeroOptimizer
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
from deepspeed.runtime.zero.utils import is_zero_supported_optimizer, ZeRORuntimeException
from deepspeed.runtime.zero.weight_quantizer import get_weight_quantizer
from deepspeed.runtime.zero.utils import (is_zero_supported_optimizer, ZeRORuntimeException, is_quantized_partition,
QUANT_SCALE_ATTR)
from deepspeed.runtime.zero.parameter_offload import DeepSpeedZeRoOffload, ZeROOrderedDict, ensure_zero_ordered_dict
from deepspeed.runtime.zero.config import ZERO_OPTIMIZATION
from deepspeed.runtime.zenflow.engine import (configure_zenflow, zenflow_step, is_zenflow_update_boundary,
Expand Down Expand Up @@ -4519,10 +4521,7 @@ def load_module_state_dict(self,
if param not in self.param_names:
raise ValueError(f"failed to find frozen {param} in named params")
name = self.param_names[param]
if hasattr(param, 'ds_id'):
param.ds_tensor.data.copy_(saved_frozen_params[name].data)
else:
param.data.copy_(saved_frozen_params[name].data)
self._restore_frozen_param_fragment(param, saved_frozen_params[name].data)

def _get_zero_ckpt_prefix(self, dp_rank, bf16_mode):
return f'{"bf16_" if bf16_mode else ""}zero_pp_rank_{dp_rank}'
Expand Down Expand Up @@ -5726,7 +5725,34 @@ def _get_param_shape_func(self, param):
return param.ds_shape if hasattr(param, 'ds_id') else param.shape

def _get_param_fragment_func(self, param):
return param.ds_tensor.detach().cpu() if hasattr(param, 'ds_id') else param.detach().cpu()
tensor = param.ds_tensor if hasattr(param, 'ds_id') else param
if is_quantized_partition(tensor):
# Checkpoints store full-precision fragments; raw int8 codes have no scales.
tensor = get_weight_quantizer().dequantize(tensor.data,
getattr(tensor, QUANT_SCALE_ATTR),
dtype=param.dtype)
return tensor.detach().cpu()

def _restore_frozen_param_fragment(self, param, saved):
if saved.dtype == torch.int8:
raise RuntimeError("This checkpoint stores frozen parameter fragments as int8 codes without their "
"scales, so the frozen weights cannot be restored. Reload the base model "
"weights and save a new checkpoint with this version.")

if not hasattr(param, 'ds_id'):
param.data.copy_(saved.to(param.device))
return

tensor = param.ds_tensor
if not is_quantized_partition(tensor):
tensor.data.copy_(saved.to(tensor.device))
return

restored = get_weight_quantizer().dequantize(tensor.data, getattr(tensor, QUANT_SCALE_ATTR), dtype=param.dtype)
restored.copy_(saved.to(restored.device))
quantized, scale = get_weight_quantizer().quantize(restored)
tensor.data = quantized
setattr(tensor, QUANT_SCALE_ATTR, scale)

def _get_zero_frozen_param_attributes(self, attr_func):
frozen_param_fragments = OrderedDict()
Expand Down
228 changes: 103 additions & 125 deletions deepspeed/runtime/zero/partition_parameters.py

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion deepspeed/runtime/zero/partitioned_param_coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@ def __all_gather_params(self, params: Set[Parameter], forward: bool) -> None:
quantized_params = []
nonquantized_params = []
for param in params:
if hasattr(param.ds_tensor, 'ds_quant_scale'):
if is_quantized_param(param):
quantized_params.append(param)
else:
nonquantized_params.append(param)
Expand Down
27 changes: 17 additions & 10 deletions deepspeed/runtime/zero/stage3.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,14 @@
is_invalid_grad_norm, is_model_parallel_parameter, is_optimized_parameter,
mask_nan_or_inf_with_val_inplace)
from deepspeed.runtime.zero.partition_parameters import *
from deepspeed.runtime.zero.weight_quantizer import get_weight_quantizer
from deepspeed.runtime.zero.config import ZeroStageEnum
from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum, OffloadStateTypeEnum
from deepspeed.runtime.zero.parameter_offload import DeepSpeedZeRoOffload
import deepspeed.runtime.zenflow.engine_stage3 as zf_engine_stage3
from deepspeed.runtime.zero.utils import ZeRORuntimeException, get_mapping_to_flat_buffer, defragment, get_norm_dtype
from deepspeed.runtime.zero.utils import (ZeRORuntimeException, get_mapping_to_flat_buffer, defragment, get_norm_dtype,
is_quantized_partition, should_quantize_nontrainable_partition,
QUANT_SCALE_ATTR)
from deepspeed.runtime.zero.offload_states import (offload_adam_states, reload_adam_states,
unpin_offloaded_optimizer_states)
from deepspeed.ops.adam import DeepSpeedCPUAdam
Expand Down Expand Up @@ -2422,14 +2425,16 @@ def quantize_nontrainable_params(self):
"Warning: quantize_nontrainable_params() called with zero_quantized_nontrainable_weights disabled, return without doing anything",
force=True)
return
quantizer_module = CUDAQuantizer()
quantizer_module = get_weight_quantizer()

def quantize_dstensor(tensor):
assert tensor.dtype == torch.float16, f"quantize_dstensor() expects tensor.dtype == torch.float16, got {tensor.dtype}"
assert tensor.dtype == torch.float16, (
f"zero_quantized_nontrainable_weights requires fp16 partitions, got {tensor.dtype}")
partition_size = tensor.ds_numel
ds_status = tensor.status
final_location = tensor.final_location
tensor, tensor.ds_quant_scale = quantizer_module.quantize(tensor)
tensor, scale = quantizer_module.quantize(tensor)
setattr(tensor, QUANT_SCALE_ATTR, scale)
tensor.ds_numel = partition_size
tensor.status = ds_status
tensor.final_location = final_location
Expand All @@ -2440,12 +2445,14 @@ def quantize_dstensor(tensor):
if hasattr(param, "ds_tensor") and (param.ds_tensor.numel() <= 2048 or param.ds_numel <= 500000):
# skip small parameters
continue
if hasattr(param,
"ds_tensor") and not param.requires_grad and not hasattr(param.ds_tensor, "ds_quant_scale"):
param.ds_tensor = quantize_dstensor(param.ds_tensor)
if hasattr(param, "ds_secondary_tensor") and not param.requires_grad and not hasattr(
param.ds_secondary_tensor, "ds_quant_scale") and param.ds_secondary_tensor is not None:
param.ds_secondary_tensor = quantize_dstensor(param.ds_secondary_tensor)
ds_tensor = getattr(param, "ds_tensor", None)
if not is_quantized_partition(ds_tensor) and should_quantize_nontrainable_partition(
param, ds_tensor, True):
param.ds_tensor = quantize_dstensor(ds_tensor)
secondary_tensor = getattr(param, "ds_secondary_tensor", None)
if not is_quantized_partition(secondary_tensor) and should_quantize_nontrainable_partition(
param, secondary_tensor, True):
param.ds_secondary_tensor = quantize_dstensor(secondary_tensor)
get_accelerator().synchronize()

def flatten_and_print(self, message, tensors, start=0, n=5):
Expand Down
40 changes: 40 additions & 0 deletions deepspeed/runtime/zero/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,50 @@
from deepspeed.utils.nvtx import instrument_w_nvtx
from deepspeed.accelerator import get_accelerator
from deepspeed.runtime.utils import get_only_unique_item
from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum

# ensure we only warn once, otherwise every iteration will trigger a warning
warned = False

QUANT_SCALE_ATTR = "ds_quant_scale"


def is_quantized_partition(tensor):
"""Whether a ZeRO partition's storage holds quantized codes."""
return tensor is not None and hasattr(tensor, QUANT_SCALE_ATTR)


def active_partition(param, use_secondary_tensor=None):
"""The partition tensor a fetch reads; defaults to the secondary tensor when present."""
if use_secondary_tensor is None:
use_secondary_tensor = getattr(param, "ds_secondary_tensor", None) is not None
return param.ds_secondary_tensor if use_secondary_tensor else param.ds_tensor


def is_quantized_param(param, use_secondary_tensor=None):
return is_quantized_partition(active_partition(param, use_secondary_tensor))


def should_quantize_nontrainable_partition(param, tensor, enabled):
"""Whether frozen storage can be quantized in place.

CPU- and NVMe-offloaded partitions stay unquantized: the quantizer runs on
the accelerator, so rebinding their storage would move it back to the
accelerator and defeat the offload. An NVMe partition also points into the
swapper buffer, where the bytes on disk would remain unquantized. The
partition length must also fit the quantizer's int8 grouping.
"""
if not enabled or param.requires_grad or tensor is None:
return False
if getattr(tensor, "final_location", None) == OffloadDeviceEnum.nvme:
return False
if tensor.device.type != get_accelerator().device_name():
logger.warning_once("zero_quantized_nontrainable_weights: frozen partitions stored on "
f"{tensor.device.type} stay unquantized")
return False
numel = tensor.numel()
return numel >= 8 and numel % 8 == 0


def _initialize_parameter_parallel_groups(parameter_parallel_size=None):
data_parallel_size = int(dist.get_world_size())
Expand Down
77 changes: 77 additions & 0 deletions deepspeed/runtime/zero/weight_quantizer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: Apache-2.0

# DeepSpeed Team

import math

import torch

from deepspeed.accelerator import get_accelerator


class ZeROWeightQuantizer:
"""Adapter between ZeRO's symmetric int8 weight quantization and the accelerator's quantizer op.

The grouping is a greedy search for a valid, fast group count, not a search
for the grouping that minimizes quantization error.
"""

async_flag = True
target_group_size = 8000 # empirically good around 4k; keep the target below 8k
group_size_cache = dict()
backend_module = None

def __init__(self) -> None:
if ZeROWeightQuantizer.backend_module is None:
from deepspeed.ops.op_builder import QuantizerBuilder
ZeROWeightQuantizer.backend_module = QuantizerBuilder().load()

def quantize(self, param, groups=None):
if groups is None:
try:
groups = self.group_size_cache[param.numel()]
except KeyError:
groups = math.ceil(param.numel() / self.target_group_size)
while groups < param.numel():
if param.numel() % (8 * groups) == 0:
break
groups += 1
while True:
if param.numel() % (8 * groups * 2) == 0 and param.numel(
) / groups > self.target_group_size: # hard limit of 16k group size
groups *= 2
else:
break
assert param.numel() % (8 * groups) == 0, (
f"Quantized weight requires the number of weights to be a multiple of 8; "
f"{param.numel()} is not divisible by 8*{groups}")
assert (param.numel() / groups < 16000), f"{param.numel()} / {groups} is larger than 16k"
assert param.numel() > groups, (
f"Greedy grouping cannot find a group size for input tensor of size {param.numel()}")
self.group_size_cache[param.numel()] = groups
# The backend reads fp16; a bf16 input would be reinterpreted. Convert on
# the way in; dequantize casts back to the caller's dtype.
param = param.to(get_accelerator().device_name(), dtype=torch.half)
return self.backend_module.quantize(param, groups, 8, self.backend_module.Symmetric)

def dequantize(self, quantized_param, scale, dtype=None):
dequantized = self.backend_module.dequantize(quantized_param, scale, scale.numel(), 8,
self.backend_module.Symmetric)
if dtype is not None and dequantized.dtype != dtype:
dequantized = dequantized.to(dtype)
return dequantized


# Historic name, kept for import compatibility.
CUDAQuantizer = ZeROWeightQuantizer

_weight_quantizer = None


def get_weight_quantizer():
"""Return the process-wide ZeRO weight quantizer, creating it on first use."""
global _weight_quantizer
if _weight_quantizer is None:
_weight_quantizer = ZeROWeightQuantizer()
return _weight_quantizer
9 changes: 8 additions & 1 deletion docs/_pages/config-json.md
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,7 @@ Enabling and configuring ZeRO memory optimizations
"zero_hpz_partition_size": 1,
"zero_quantized_weights": [true|false],
"zero_quantized_gradients": [true|false],
"zero_quantized_nontrainable_weights": [true|false],
"log_trace_cache_warnings": [true|false],
}
```
Expand Down Expand Up @@ -584,7 +585,7 @@ Most users can leave `sub_group_size` at its default value when not using NVMe o

| Description | Default |
| ----------------------------------------------------------------------------------------------------------------------------------- | ------- |
| Number of ranks in hiearchical partitioning ZeRO (hpZ) secondary tensor group of ZeRO++, default is 1 meaning no hpZ, ideal is number of ranks (gpus) per node. | `1` |
| Number of ranks in hierarchical partitioning ZeRO (hpZ) secondary tensor group of ZeRO++, default is 1 meaning no hpZ, ideal is number of ranks (gpus) per node. | `1` |

***zero_quantized_weights***: [boolean]

Expand All @@ -598,6 +599,12 @@ Most users can leave `sub_group_size` at its default value when not using NVMe o
| ----------------------------------------------------------------------------------------------------------------------------------- | ------- |
|Boolean indicating whether to enable communication efficient quantized gradients of ZeRO++. | `False` |

***zero_quantized_nontrainable_weights***: [boolean]

| Description | Default |
| ----------------------------------------------------------------------------------------------------------------------------------- | ------- |
|Boolean indicating whether to keep the frozen (non-trainable) weights of a ZeRO-3 model in quantized storage. Requires an fp16 model. | `False` |

<i>**log_trace_cache_warnings**</i>: [boolean]

| Description | Default |
Expand Down
2 changes: 2 additions & 0 deletions docs/_tutorials/mixed_precision_zeropp.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ An example snippet of deepspeed configurations with all MixZ++ optimization enab
```
Note that for multi-node training, the `"zero_hpz_partition_size"` should be set to the number of GPUs per node. For example, if you have 8 GPUs per node, then `"zero_hpz_partition_size"` should be set to 8. For single-node training, the `"zero_hpz_partition_size"` should not be set.

`zero_quantized_nontrainable_weights` requires an fp16 base model. bf16 and fp32 models are not supported. Only accelerator-resident frozen partitions are quantized; CPU-offloaded frozen partitions stay unquantized.

### Training Script Changes
DeepSpeed engine will identify the LoRA frozen parameters if the LoRA model is passed when DeepSpeed initializes. However, the popular implementation is to initialize a base model and then convert to LoRA model later. In such cases, users need to explicitly call DeepSpeed engine after LoRA model is converted. This is only a 1-line effort. An example snippet of training script is shown below:

Expand Down
Loading
Loading