id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
10,254
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config DUMP_STATE = 'dump_state' DUMP_STATE_DEFAULT = False def get_scalar_param(param_dict, param_name, param_default_value): def get_dump_state(param_dict): return get_scalar_param(param_dict, DUMP_STATE, DUMP_STATE_DEFAULT)
null
10,255
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config GRADIENT_CLIPPING = 'gradient_clipping' GRADIENT_CLIPPING_DEFAULT = 0. def get_scalar_param(param_dict, param_name, param_default_value): return param_dict.get(param_name, param_default_value) def get_gradient_clipping(param_dict): return get_scalar_param(param_dict, GRADIENT_CLIPPING, GRADIENT_CLIPPING_DEFAULT)
null
10,256
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config def get_sparse_dense_config(sparsity): block = get_scalar_param(sparsity, SPARSE_BLOCK, SPARSE_BLOCK_DEFAULT) return {SPARSE_MODE: SPARSE_DENSE_MODE, SPARSE_BLOCK: block} def get_sparse_fixed_config(sparsity): block = get_scalar_param(sparsity, SPARSE_BLOCK, SPARSE_BLOCK_DEFAULT) different_layout_per_head = get_scalar_param( sparsity, SPARSE_DIFFERENT_LAYOUT_PER_HEAD, SPARSE_DIFFERENT_LAYOUT_PER_HEAD_DEFAULT, ) num_local_blocks = get_scalar_param(sparsity, SPARSE_NUM_LOCAL_BLOCKS, SPARSE_NUM_LOCAL_BLOCKS_DEFAULT) num_global_blocks = get_scalar_param(sparsity, SPARSE_NUM_GLOBAL_BLOCKS, SPARSE_NUM_GLOBAL_BLOCKS_DEFAULT) attention = get_scalar_param(sparsity, SPARSE_ATTENTION_TYPE, SPARSE_ATTENTION_TYPE_DEFAULT) horizontal_global_attention = get_scalar_param( sparsity, SPARSE_HORIZONTAL_GLOBAL_ATTENTION, SPARSE_HORIZONTAL_GLOBAL_ATTENTION_DEFAULT, ) num_different_global_patterns = get_scalar_param( sparsity, SPARSE_NUM_DIFFERENT_GLOBAL_PATTERNS, SPARSE_NUM_DIFFERENT_GLOBAL_PATTERNS_DEFAULT, ) return { SPARSE_MODE: SPARSE_FIXED_MODE, SPARSE_BLOCK: block, SPARSE_DIFFERENT_LAYOUT_PER_HEAD: different_layout_per_head, SPARSE_NUM_LOCAL_BLOCKS: num_local_blocks, SPARSE_NUM_GLOBAL_BLOCKS: num_global_blocks, SPARSE_ATTENTION_TYPE: attention, SPARSE_HORIZONTAL_GLOBAL_ATTENTION: horizontal_global_attention, SPARSE_NUM_DIFFERENT_GLOBAL_PATTERNS: num_different_global_patterns, } def get_sparse_variable_config(sparsity): block = get_scalar_param(sparsity, SPARSE_BLOCK, SPARSE_BLOCK_DEFAULT) different_layout_per_head = get_scalar_param( sparsity, SPARSE_DIFFERENT_LAYOUT_PER_HEAD, SPARSE_DIFFERENT_LAYOUT_PER_HEAD_DEFAULT, ) num_random_blocks = get_scalar_param(sparsity, SPARSE_NUM_RANDOM_BLOCKS, SPARSE_NUM_RANDOM_BLOCKS_DEFAULT) local_window_blocks = get_scalar_param(sparsity, SPARSE_LOCAL_WINDOW_BLOCKS, SPARSE_LOCAL_WINDOW_BLOCKS_DEFAULT) global_block_indices = get_scalar_param(sparsity, SPARSE_GLOBAL_BLOCK_INDICES, SPARSE_GLOBAL_BLOCK_INDICES_DEFAULT) global_block_end_indices = get_scalar_param( sparsity, SPARSE_GLOBAL_BLOCK_END_INDICES, SPARSE_GLOBAL_BLOCK_END_INDICES_DEFAULT, ) attention = get_scalar_param(sparsity, SPARSE_ATTENTION_TYPE, SPARSE_ATTENTION_TYPE_DEFAULT) horizontal_global_attention = get_scalar_param( sparsity, SPARSE_HORIZONTAL_GLOBAL_ATTENTION, SPARSE_HORIZONTAL_GLOBAL_ATTENTION_DEFAULT, ) return { SPARSE_MODE: SPARSE_VARIABLE_MODE, SPARSE_BLOCK: block, SPARSE_DIFFERENT_LAYOUT_PER_HEAD: different_layout_per_head, SPARSE_NUM_RANDOM_BLOCKS: num_random_blocks, SPARSE_LOCAL_WINDOW_BLOCKS: local_window_blocks, SPARSE_GLOBAL_BLOCK_INDICES: global_block_indices, SPARSE_GLOBAL_BLOCK_END_INDICES: global_block_end_indices, SPARSE_ATTENTION_TYPE: attention, SPARSE_HORIZONTAL_GLOBAL_ATTENTION: horizontal_global_attention, } def get_sparse_bigbird_config(sparsity): block = get_scalar_param(sparsity, SPARSE_BLOCK, SPARSE_BLOCK_DEFAULT) different_layout_per_head = get_scalar_param( sparsity, SPARSE_DIFFERENT_LAYOUT_PER_HEAD, SPARSE_DIFFERENT_LAYOUT_PER_HEAD_DEFAULT, ) num_random_blocks = get_scalar_param(sparsity, SPARSE_NUM_RANDOM_BLOCKS, SPARSE_NUM_RANDOM_BLOCKS_DEFAULT) num_sliding_window_blocks = get_scalar_param( sparsity, SPARSE_NUM_SLIDING_WINDOW_BLOCKS, SPARSE_NUM_SLIDING_WINDOW_BLOCKS_DEFAULT, ) num_global_blocks = get_scalar_param(sparsity, SPARSE_NUM_GLOBAL_BLOCKS, SPARSE_NUM_GLOBAL_BLOCKS_DEFAULT) return { SPARSE_MODE: SPARSE_BIGBIRD_MODE, SPARSE_BLOCK: block, SPARSE_DIFFERENT_LAYOUT_PER_HEAD: different_layout_per_head, SPARSE_NUM_RANDOM_BLOCKS: num_random_blocks, SPARSE_NUM_SLIDING_WINDOW_BLOCKS: num_sliding_window_blocks, SPARSE_NUM_GLOBAL_BLOCKS: num_global_blocks, } def get_sparse_bslongformer_config(sparsity): block = get_scalar_param(sparsity, SPARSE_BLOCK, SPARSE_BLOCK_DEFAULT) different_layout_per_head = get_scalar_param( sparsity, SPARSE_DIFFERENT_LAYOUT_PER_HEAD, SPARSE_DIFFERENT_LAYOUT_PER_HEAD_DEFAULT, ) num_sliding_window_blocks = get_scalar_param( sparsity, SPARSE_NUM_SLIDING_WINDOW_BLOCKS, SPARSE_NUM_SLIDING_WINDOW_BLOCKS_DEFAULT, ) global_block_indices = get_scalar_param(sparsity, SPARSE_GLOBAL_BLOCK_INDICES, SPARSE_GLOBAL_BLOCK_INDICES_DEFAULT) global_block_end_indices = get_scalar_param( sparsity, SPARSE_GLOBAL_BLOCK_END_INDICES, SPARSE_GLOBAL_BLOCK_END_INDICES_DEFAULT, ) return { SPARSE_MODE: SPARSE_BSLONGFORMER_MODE, SPARSE_BLOCK: block, SPARSE_DIFFERENT_LAYOUT_PER_HEAD: different_layout_per_head, SPARSE_NUM_SLIDING_WINDOW_BLOCKS: num_sliding_window_blocks, SPARSE_GLOBAL_BLOCK_INDICES: global_block_indices, SPARSE_GLOBAL_BLOCK_END_INDICES: global_block_end_indices, } def get_sparse_attention_mode(param_dict): if SPARSE_MODE in param_dict.keys(): return param_dict[SPARSE_MODE] else: return SPARSE_MODE_DEFAULT SPARSE_ATTENTION = "sparse_attention" SPARSE_DENSE_MODE = "dense" SPARSE_FIXED_MODE = "fixed" SPARSE_VARIABLE_MODE = "variable" SPARSE_BIGBIRD_MODE = "bigbird" SPARSE_BSLONGFORMER_MODE = "bslongformer" def get_sparse_attention(param_dict): if SPARSE_ATTENTION in param_dict.keys(): sparsity = param_dict[SPARSE_ATTENTION] mode = get_sparse_attention_mode(sparsity) if mode == SPARSE_DENSE_MODE: return get_sparse_dense_config(sparsity) elif mode == SPARSE_FIXED_MODE: return get_sparse_fixed_config(sparsity) elif mode == SPARSE_VARIABLE_MODE: return get_sparse_variable_config(sparsity) elif mode == SPARSE_BIGBIRD_MODE: return get_sparse_bigbird_config(sparsity) elif mode == SPARSE_BSLONGFORMER_MODE: return get_sparse_bslongformer_config(sparsity) else: raise NotImplementedError( f"Given sparsity mode, {mode}, has not been implemented yet!") else: return None
null
10,257
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config SPARSE_ATTENTION_TYPE = "attention" SPARSE_ATTENTION_TYPE_DEFAULT = "bidirectional" def get_sparse_attention_type(param_dict): if SPARSE_ATTENTION_TYPE in param_dict.keys(): return param_dict[SPARSE_ATTENTION_TYPE] else: return SPARSE_ATTENTION_TYPE_DEFAULT
null
10,258
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config The provided code snippet includes necessary dependencies for implementing the `get_pipeline_config` function. Write a Python function `def get_pipeline_config(param_dict)` to solve the following problem: Parses pipeline engine configuration. Here is the function: def get_pipeline_config(param_dict): """Parses pipeline engine configuration. """ default_pipeline = { "stages": "auto", "partition": "best", "seed_layers": False, "activation_checkpoint_interval": 0, } config = default_pipeline for key, val in param_dict.get("pipeline", {}).items(): config[key] = val return config
Parses pipeline engine configuration.
10,259
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config def get_optimizer_params(param_dict): if (get_optimizer_name(param_dict) is not None and OPTIMIZER_PARAMS in param_dict[OPTIMIZER].keys()): return param_dict[OPTIMIZER][OPTIMIZER_PARAMS] else: return None MAX_GRAD_NORM = 'max_grad_norm' def get_optimizer_gradient_clipping(param_dict): optimizer_params = get_optimizer_params(param_dict) if optimizer_params is not None and MAX_GRAD_NORM in optimizer_params.keys(): return optimizer_params[MAX_GRAD_NORM] else: return None
null
10,260
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config OPTIMIZER = "optimizer" LEGACY_FUSION = "legacy_fusion" LEGACY_FUSION_DEFAULT = False def get_optimizer_legacy_fusion(param_dict): if OPTIMIZER in param_dict.keys() and LEGACY_FUSION in param_dict[OPTIMIZER].keys(): return param_dict[OPTIMIZER][LEGACY_FUSION] else: return LEGACY_FUSION_DEFAULT
null
10,261
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config ZERO_ALLOW_UNTESTED_OPTIMIZER = "zero_allow_untested_optimizer" ZERO_ALLOW_UNTESTED_OPTIMIZER_DEFAULT = False def get_scalar_param(param_dict, param_name, param_default_value): return param_dict.get(param_name, param_default_value) def get_zero_allow_untested_optimizer(param_dict): return get_scalar_param(param_dict, ZERO_ALLOW_UNTESTED_OPTIMIZER, ZERO_ALLOW_UNTESTED_OPTIMIZER_DEFAULT)
null
10,262
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config def get_scheduler_name(param_dict): if SCHEDULER in param_dict.keys() and TYPE in param_dict[SCHEDULER].keys(): return param_dict[SCHEDULER][TYPE] else: return SCHEDULER_TYPE_DEFAULT SCHEDULER = "scheduler" SCHEDULER_PARAMS = "params" def get_scheduler_params(param_dict): if (get_scheduler_name(param_dict) is not None and SCHEDULER_PARAMS in param_dict[SCHEDULER].keys()): return param_dict[SCHEDULER][SCHEDULER_PARAMS] else: return None
null
10,263
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config TRAIN_BATCH_SIZE = "train_batch_size" TRAIN_BATCH_SIZE_DEFAULT = None def get_scalar_param(param_dict, param_name, param_default_value): return param_dict.get(param_name, param_default_value) def get_train_batch_size(param_dict): return get_scalar_param(param_dict, TRAIN_BATCH_SIZE, TRAIN_BATCH_SIZE_DEFAULT)
null
10,264
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config TRAIN_MICRO_BATCH_SIZE_PER_GPU = ''' TRAIN_MICRO_BATCH_SIZE_PER_GPU is defined in this format: "train_micro_batch_size_per_gpu": 1 ''' TRAIN_MICRO_BATCH_SIZE_PER_GPU = "train_micro_batch_size_per_gpu" TRAIN_MICRO_BATCH_SIZE_PER_GPU_DEFAULT = None def get_scalar_param(param_dict, param_name, param_default_value): def get_train_micro_batch_size_per_gpu(param_dict): return get_scalar_param( param_dict, TRAIN_MICRO_BATCH_SIZE_PER_GPU, TRAIN_MICRO_BATCH_SIZE_PER_GPU_DEFAULT, )
null
10,265
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config WALL_CLOCK_BREAKDOWN = 'wall_clock_breakdown' WALL_CLOCK_BREAKDOWN_DEFAULT = False def get_scalar_param(param_dict, param_name, param_default_value): return param_dict.get(param_name, param_default_value) def get_wall_clock_breakdown(param_dict): return get_scalar_param(param_dict, WALL_CLOCK_BREAKDOWN, WALL_CLOCK_BREAKDOWN_DEFAULT)
null
10,266
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config MEMORY_BREAKDOWN = 'memory_breakdown' MEMORY_BREAKDOWN_DEFAULT = False def get_scalar_param(param_dict, param_name, param_default_value): return param_dict.get(param_name, param_default_value) def get_memory_breakdown(param_dict): return get_scalar_param(param_dict, MEMORY_BREAKDOWN, MEMORY_BREAKDOWN_DEFAULT)
null
10,267
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config def get_eigenvalue_enabled(param_dict): if EIGENVALUE in param_dict.keys(): return get_scalar_param(param_dict[EIGENVALUE], EIGENVALUE_ENABLED, EIGENVALUE_ENABLED_DEFAULT) else: return EIGENVALUE_ENABLED_DEFAULT def get_eigenvalue_verbose(param_dict): if EIGENVALUE in param_dict.keys(): return get_scalar_param(param_dict[EIGENVALUE], EIGENVALUE_VERBOSE, EIGENVALUE_VERBOSE_DEFAULT) else: return EIGENVALUE_VERBOSE_DEFAULT def get_eigenvalue_max_iter(param_dict): if EIGENVALUE in param_dict.keys(): return get_scalar_param(param_dict[EIGENVALUE], EIGENVALUE_MAX_ITER, EIGENVALUE_MAX_ITER_DEFAULT) else: return EIGENVALUE_MAX_ITER_DEFAULT def get_eigenvalue_tol(param_dict): if EIGENVALUE in param_dict.keys(): return get_scalar_param(param_dict[EIGENVALUE], EIGENVALUE_TOL, EIGENVALUE_TOL_DEFAULT) else: return EIGENVALUE_TOL_DEFAULT def get_eigenvalue_stability(param_dict): if EIGENVALUE in param_dict.keys(): return get_scalar_param(param_dict[EIGENVALUE], EIGENVALUE_STABILITY, EIGENVALUE_STABILITY_DEFAULT) else: return EIGENVALUE_STABILITY_DEFAULT def get_eigenvalue_gas_boundary_resolution(param_dict): if EIGENVALUE in param_dict.keys(): return get_scalar_param( param_dict[EIGENVALUE], EIGENVALUE_GAS_BOUNDARY_RESOLUTION, EIGENVALUE_GAS_BOUNDARY_RESOLUTION_DEFAULT, ) else: return EIGENVALUE_GAS_BOUNDARY_RESOLUTION_DEFAULT def get_eigenvalue_layer_name(param_dict): if EIGENVALUE in param_dict.keys(): return get_scalar_param(param_dict[EIGENVALUE], EIGENVALUE_LAYER_NAME, EIGENVALUE_LAYER_NAME_DEFAULT) else: return EIGENVALUE_LAYER_NAME_DEFAULT def get_eigenvalue_layer_num(param_dict): if EIGENVALUE in param_dict.keys(): return get_scalar_param(param_dict[EIGENVALUE], EIGENVALUE_LAYER_NUM, EIGENVALUE_LAYER_NUM_DEFAULT) else: return EIGENVALUE_LAYER_NUM_DEFAULT EIGENVALUE_ENABLED_DEFAULT = False EIGENVALUE_VERBOSE_DEFAULT = False EIGENVALUE_MAX_ITER_DEFAULT = 100 EIGENVALUE_TOL_DEFAULT = 1e-2 EIGENVALUE_STABILITY_DEFAULT = 1e-6 EIGENVALUE_GAS_BOUNDARY_RESOLUTION_DEFAULT = 1 EIGENVALUE_LAYER_NAME_DEFAULT = "bert.encoder.layer" EIGENVALUE_LAYER_NUM_DEFAULT = 0 def get_quantize_enabled(param_dict): if COMPRESSION_TRAINING not in param_dict.keys(): return False sub_param_dict = param_dict[COMPRESSION_TRAINING] output = get_weight_quantization_shared_parameters(sub_param_dict) return output[WEIGHT_QUANTIZE_ENABLED] def get_eigenvalue_config(param_dict): if get_quantize_enabled(param_dict): param_dict = param_dict[QUANTIZE_TRAINING] assert not get_eigenvalue_enabled(param_dict), "Eigenvalue based MoQ is temporarily disabled" return ( get_eigenvalue_enabled(param_dict), get_eigenvalue_verbose(param_dict), get_eigenvalue_max_iter(param_dict), get_eigenvalue_tol(param_dict), get_eigenvalue_stability(param_dict), get_eigenvalue_gas_boundary_resolution(param_dict), get_eigenvalue_layer_name(param_dict), get_eigenvalue_layer_num(param_dict), ) else: return ( EIGENVALUE_ENABLED_DEFAULT, EIGENVALUE_VERBOSE_DEFAULT, EIGENVALUE_MAX_ITER_DEFAULT, EIGENVALUE_TOL_DEFAULT, EIGENVALUE_STABILITY_DEFAULT, EIGENVALUE_GAS_BOUNDARY_RESOLUTION_DEFAULT, EIGENVALUE_LAYER_NAME_DEFAULT, EIGENVALUE_LAYER_NUM_DEFAULT, )
null
10,268
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config CHECKPOINT = "checkpoint" def get_checkpoint_params(param_dict): return param_dict.get(CHECKPOINT, {})
null
10,269
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config DATA_TYPES = "data_types" def get_data_types_params(param_dict): return param_dict.get(DATA_TYPES, {})
null
10,270
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config class DeepSpeedConfigError(Exception): pass CHECKPOINT_TAG_VALIDATION = "tag_validation" CHECKPOINT_TAG_VALIDATION_DEFAULT = ValidationMode.WARN CHECKPOINT_TAG_VALIDATION_MODES = [ ValidationMode.WARN, ValidationMode.IGNORE, ValidationMode.FAIL ] def get_checkpoint_tag_validation_mode(checkpoint_params): tag_validation_mode = checkpoint_params.get(CHECKPOINT_TAG_VALIDATION, CHECKPOINT_TAG_VALIDATION_DEFAULT) tag_validation_mode = tag_validation_mode.upper() if tag_validation_mode in CHECKPOINT_TAG_VALIDATION_MODES: return tag_validation_mode else: raise DeepSpeedConfigError( "Checkpoint config contains invalid tag_validation " f"value of {tag_validation_mode}, expecting one of {CHECKPOINT_TAG_VALIDATION_MODES}" )
null
10,271
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config class DeepSpeedConfigError(Exception): pass CHECKPOINT_PARALLEL_WRITE = "parallel_write" CHECKPOINT_PARALLEL_WRITE_PIPELINE_STAGE = "pipeline_stage" CHECKPOINT_PARALLEL_WRITE_PIPELINE_STAGE_DEFAULT = False def get_checkpoint_parallel_write_pipeline(checkpoint_params): par_write_params = checkpoint_params.get(CHECKPOINT_PARALLEL_WRITE, {}) par_write_pipeline = par_write_params.get( CHECKPOINT_PARALLEL_WRITE_PIPELINE_STAGE, CHECKPOINT_PARALLEL_WRITE_PIPELINE_STAGE_DEFAULT) if par_write_pipeline in [True, False]: return par_write_pipeline else: raise DeepSpeedConfigError( "checkpoint::parallel_write::pipeline_stage " f"value of '{par_write_pipeline}' is invalid, expecting: true or false")
null
10,272
import os from typing import Union import torch import json import copy import base64 from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( get_scalar_param, dict_raise_error_on_duplicate_keys, ScientificNotationEncoder, ) from .zero.config import get_zero_config, ZeroStageEnum from .activation_checkpointing.config import DeepSpeedActivationCheckpointingConfig from ..comm.config import DeepSpeedCommsConfig from ..monitor.config import DeepSpeedMonitorConfig from deepspeed import comm as dist from ..git_version_info import version as __version__ from ..utils import logger from ..elasticity import ( elasticity_enabled, compute_elastic_config, ensure_immutable_elastic_config, ) from ..elasticity.config import ElasticityConfigError from ..elasticity.constants import ( ELASTICITY, IGNORE_NON_ELASTIC_BATCH_INFO, IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, MODEL_PARLLEL_SIZE, MODEL_PARLLEL_SIZE_DEFAULT, NUM_GPUS_PER_NODE, NUM_GPUS_PER_NODE_DEFAULT, ) from ..profiling.config import DeepSpeedFlopsProfilerConfig from ..autotuning.config import DeepSpeedAutotuningConfig from ..nebula.config import DeepSpeedNebulaConfig from ..compression.config import get_compression_config, get_quantize_enabled from ..compression.constants import * from .swap_tensor.aio_config import get_aio_config DATALOADER_DROP_LAST = "dataloader_drop_last" DATALOADER_DROP_LAST_DEFAULT = False def get_scalar_param(param_dict, param_name, param_default_value): return param_dict.get(param_name, param_default_value) def get_dataloader_drop_last(param_dict): return get_scalar_param(param_dict, DATALOADER_DROP_LAST, DATALOADER_DROP_LAST_DEFAULT)
null
10,273
from dataclasses import dataclass import collections from collections import UserDict from typing import Deque, Set from torch.cuda import Event, Stream from deepspeed import comm as dist from deepspeed.utils.logging import logger from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.partition_parameters import * from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus from deepspeed.utils.debug import debug_module2name_id, debug_param2name_id logger = LoggerFactory.create_logger(name="DeepSpeed", level=logging.INFO) def debug_rank0(message: str) -> None: if dist.get_rank() == 0: logger.debug(message)
null
10,274
from dataclasses import dataclass import collections from collections import UserDict from typing import Deque, Set from torch.cuda import Event, Stream from deepspeed import comm as dist from deepspeed.utils.logging import logger from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.partition_parameters import * from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus from deepspeed.utils.debug import debug_module2name_id, debug_param2name_id def get_all_parameters(sub_module, recurse=False): return itertools.chain(sub_module.named_parameters(recurse=recurse), sub_module.ds_external_parameters()) def iter_params(module: Module, recurse=False) -> Iterable[Parameter]: return map(lambda pair: pair[1], get_all_parameters(module, recurse))
null
10,275
import os from typing import List import torch from deepspeed import comm as dist from deepspeed.utils import logger from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.adam import FusedAdam from deepspeed.utils.nvtx import instrument_w_nvtx def _initialize_parameter_parallel_groups(parameter_parallel_size=None): data_parallel_size = int(dist.get_world_size()) parameter_parallel_size = parameter_parallel_size or data_parallel_size logger.info("data_parallel_size: %s, parameter_parallel_size: %s", data_parallel_size, parameter_parallel_size) assert data_parallel_size % parameter_parallel_size == 0, \ 'world size should be divisible by parameter parallel size' rank = dist.get_rank() my_group = None for i in range(data_parallel_size // parameter_parallel_size): ranks = range(i * parameter_parallel_size, (i + 1) * parameter_parallel_size) group = dist.new_group(ranks) if rank in ranks: my_group = group return my_group
null
10,276
import os from typing import List import torch from deepspeed import comm as dist from deepspeed.utils import logger from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.adam import FusedAdam from deepspeed.utils.nvtx import instrument_w_nvtx ZERO_SUPPORTED_OPTIMIZERS = [ torch.optim.Adam, torch.optim.AdamW, FusedAdam, DeepSpeedCPUAdam ] def is_zero_supported_optimizer(optimizer): if dist.get_rank() == 0: logger.info( f'Checking ZeRO support for optimizer={optimizer.__class__.__name__} type={type(optimizer)}' ) return type(optimizer) in ZERO_SUPPORTED_OPTIMIZERS
null
10,277
import os from typing import List import torch from deepspeed import comm as dist from deepspeed.utils import logger from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.adam import FusedAdam from deepspeed.utils.nvtx import instrument_w_nvtx def get_lst_from_rank0(lst: List[int]) -> None: """ NOTE: creates both communication and synchronization overhead so should be used sparingly """ lst_tensor = torch.tensor( lst if dist.get_rank() == 0 else [-1] * len(lst), dtype=int, # device=torch.cuda.current_device(), device=torch.device('cuda:{}'.format(os.environ["LOCAL_RANK"])), requires_grad=False, ) dist.broadcast(lst_tensor, src=0, async_op=False) return list(lst_tensor.cpu().numpy()) The provided code snippet includes necessary dependencies for implementing the `assert_ints_same_as_other_ranks` function. Write a Python function `def assert_ints_same_as_other_ranks(ints: List[int]) -> None` to solve the following problem: NOTE: creates both communication and synchronization overhead so should be used sparingly takes a list of ints from each rank and ensures that they are the same across ranks, throwing an exception if they are not. Here is the function: def assert_ints_same_as_other_ranks(ints: List[int]) -> None: """ NOTE: creates both communication and synchronization overhead so should be used sparingly takes a list of ints from each rank and ensures that they are the same across ranks, throwing an exception if they are not. """ rank0_ints = get_lst_from_rank0(ints) if ints != rank0_ints: raise RuntimeError(f"disagreement between rank0 and rank{dist.get_rank()}: " f"rank0: {rank0_ints}, rank{dist.get_rank()}: {ints}")
NOTE: creates both communication and synchronization overhead so should be used sparingly takes a list of ints from each rank and ensures that they are the same across ranks, throwing an exception if they are not.
10,278
import torch import os from deepspeed import comm as dist from torch._six import inf from packaging import version as pkg_version from collections import OrderedDict from deepspeed.runtime import ZeROOptimizer from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.utils import (bwc_tensor_model_parallel_rank, get_global_norm, see_memory_usage, is_model_parallel_parameter, align_dense_tensors, all_gather_dp_groups) from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.utils import logger from deepspeed.moe.utils import is_moe_param from deepspeed.git_version_info import version from deepspeed.runtime.constants import PIPE_REPLICATED from deepspeed.checkpoint.constants import (DS_VERSION, GROUP_PADDINGS, PARTITION_COUNT, SINGLE_PARTITION_OF_FP32_GROUPS, BASE_OPTIMIZER_STATE, CLIP_GRAD, ZERO_STAGE, PARAM_SLICE_MAPPINGS) from deepspeed.utils import link_hp_params from deepspeed.checkpoint import enable_universal_checkpoint def input(msg): return
null
10,279
import torch import os from deepspeed import comm as dist from torch._six import inf from packaging import version as pkg_version from collections import OrderedDict from deepspeed.runtime import ZeROOptimizer from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.utils import (bwc_tensor_model_parallel_rank, get_global_norm, see_memory_usage, is_model_parallel_parameter, align_dense_tensors, all_gather_dp_groups) from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.utils import logger from deepspeed.moe.utils import is_moe_param from deepspeed.git_version_info import version from deepspeed.runtime.constants import PIPE_REPLICATED from deepspeed.checkpoint.constants import (DS_VERSION, GROUP_PADDINGS, PARTITION_COUNT, SINGLE_PARTITION_OF_FP32_GROUPS, BASE_OPTIMIZER_STATE, CLIP_GRAD, ZERO_STAGE, PARAM_SLICE_MAPPINGS) from deepspeed.utils import link_hp_params from deepspeed.checkpoint import enable_universal_checkpoint def split_half_float_double(tensors): dtypes = [ "torch.cuda.HalfTensor", "torch.cuda.FloatTensor", "torch.cuda.DoubleTensor", "torch.cuda.BFloat16Tensor" ] buckets = [] for i, dtype in enumerate(dtypes): bucket = [t for t in tensors if t.type() == dtype] if bucket: buckets.append(bucket) return buckets
null
10,280
import torch import os from deepspeed import comm as dist from torch._six import inf from packaging import version as pkg_version from collections import OrderedDict from deepspeed.runtime import ZeROOptimizer from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.utils import (bwc_tensor_model_parallel_rank, get_global_norm, see_memory_usage, is_model_parallel_parameter, align_dense_tensors, all_gather_dp_groups) from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.utils import logger from deepspeed.moe.utils import is_moe_param from deepspeed.git_version_info import version from deepspeed.runtime.constants import PIPE_REPLICATED from deepspeed.checkpoint.constants import (DS_VERSION, GROUP_PADDINGS, PARTITION_COUNT, SINGLE_PARTITION_OF_FP32_GROUPS, BASE_OPTIMIZER_STATE, CLIP_GRAD, ZERO_STAGE, PARAM_SLICE_MAPPINGS) from deepspeed.utils import link_hp_params from deepspeed.checkpoint import enable_universal_checkpoint def isclose(a, b, rtol=1e-09, atol=0.0): return abs(a - b) <= max(rtol * max(abs(a), abs(b)), atol)
null
10,281
import torch import os from deepspeed import comm as dist from torch._six import inf from packaging import version as pkg_version from collections import OrderedDict from deepspeed.runtime import ZeROOptimizer from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.utils import (bwc_tensor_model_parallel_rank, get_global_norm, see_memory_usage, is_model_parallel_parameter, align_dense_tensors, all_gather_dp_groups) from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.utils import logger from deepspeed.moe.utils import is_moe_param from deepspeed.git_version_info import version from deepspeed.runtime.constants import PIPE_REPLICATED from deepspeed.checkpoint.constants import (DS_VERSION, GROUP_PADDINGS, PARTITION_COUNT, SINGLE_PARTITION_OF_FP32_GROUPS, BASE_OPTIMIZER_STATE, CLIP_GRAD, ZERO_STAGE, PARAM_SLICE_MAPPINGS) from deepspeed.utils import link_hp_params from deepspeed.checkpoint import enable_universal_checkpoint def lcm(x, y): from fractions import gcd # or can import gcd from `math` in Python 3 return x * y // gcd(x, y)
null
10,282
import torch import os from deepspeed import comm as dist from torch._six import inf from packaging import version as pkg_version from collections import OrderedDict from deepspeed.runtime import ZeROOptimizer from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.utils import (bwc_tensor_model_parallel_rank, get_global_norm, see_memory_usage, is_model_parallel_parameter, align_dense_tensors, all_gather_dp_groups) from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.utils import logger from deepspeed.moe.utils import is_moe_param from deepspeed.git_version_info import version from deepspeed.runtime.constants import PIPE_REPLICATED from deepspeed.checkpoint.constants import (DS_VERSION, GROUP_PADDINGS, PARTITION_COUNT, SINGLE_PARTITION_OF_FP32_GROUPS, BASE_OPTIMIZER_STATE, CLIP_GRAD, ZERO_STAGE, PARAM_SLICE_MAPPINGS) from deepspeed.utils import link_hp_params from deepspeed.checkpoint import enable_universal_checkpoint def get_alignment_padding(tensor_list, alignment): num_elements = sum([tensor.numel() for tensor in tensor_list]) remainder = num_elements % alignment return (alignment - remainder) if remainder else remainder
null
10,283
import torch import os from deepspeed import comm as dist from torch._six import inf from packaging import version as pkg_version from collections import OrderedDict from deepspeed.runtime import ZeROOptimizer from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.utils import (bwc_tensor_model_parallel_rank, get_global_norm, see_memory_usage, is_model_parallel_parameter, align_dense_tensors, all_gather_dp_groups) from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.utils import logger from deepspeed.moe.utils import is_moe_param from deepspeed.git_version_info import version from deepspeed.runtime.constants import PIPE_REPLICATED from deepspeed.checkpoint.constants import (DS_VERSION, GROUP_PADDINGS, PARTITION_COUNT, SINGLE_PARTITION_OF_FP32_GROUPS, BASE_OPTIMIZER_STATE, CLIP_GRAD, ZERO_STAGE, PARAM_SLICE_MAPPINGS) from deepspeed.utils import link_hp_params from deepspeed.checkpoint import enable_universal_checkpoint def move_to_cpu(tensor_list): for tensor in tensor_list: tensor.data = tensor.data.cpu()
null
10,284
import torch import os from deepspeed import comm as dist from torch._six import inf from packaging import version as pkg_version from collections import OrderedDict from deepspeed.runtime import ZeROOptimizer from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.utils import (bwc_tensor_model_parallel_rank, get_global_norm, see_memory_usage, is_model_parallel_parameter, align_dense_tensors, all_gather_dp_groups) from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.utils import logger from deepspeed.moe.utils import is_moe_param from deepspeed.git_version_info import version from deepspeed.runtime.constants import PIPE_REPLICATED from deepspeed.checkpoint.constants import (DS_VERSION, GROUP_PADDINGS, PARTITION_COUNT, SINGLE_PARTITION_OF_FP32_GROUPS, BASE_OPTIMIZER_STATE, CLIP_GRAD, ZERO_STAGE, PARAM_SLICE_MAPPINGS) from deepspeed.utils import link_hp_params from deepspeed.checkpoint import enable_universal_checkpoint def print_rank_msg(msg): print(f"rank {dist.get_rank()} - {msg}")
null
10,285
import torch import os from deepspeed import comm as dist from torch._six import inf from packaging import version as pkg_version from collections import OrderedDict from deepspeed.runtime import ZeROOptimizer from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.utils import (bwc_tensor_model_parallel_rank, get_global_norm, see_memory_usage, is_model_parallel_parameter, align_dense_tensors, all_gather_dp_groups) from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.utils import logger from deepspeed.moe.utils import is_moe_param from deepspeed.git_version_info import version from deepspeed.runtime.constants import PIPE_REPLICATED from deepspeed.checkpoint.constants import (DS_VERSION, GROUP_PADDINGS, PARTITION_COUNT, SINGLE_PARTITION_OF_FP32_GROUPS, BASE_OPTIMIZER_STATE, CLIP_GRAD, ZERO_STAGE, PARAM_SLICE_MAPPINGS) from deepspeed.utils import link_hp_params from deepspeed.checkpoint import enable_universal_checkpoint def _get_padded_tensor(src_tensor, size): if src_tensor.numel() >= size: return src_tensor padded_tensor = torch.zeros(size, dtype=src_tensor.dtype, device=src_tensor.device) slice_tensor = torch.narrow(padded_tensor, 0, 0, src_tensor.numel()) slice_tensor.data.copy_(src_tensor.data) return padded_tensor
null
10,286
import torch import os from deepspeed import comm as dist from torch._six import inf from packaging import version as pkg_version from collections import OrderedDict from deepspeed.runtime import ZeROOptimizer from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.utils import (bwc_tensor_model_parallel_rank, get_global_norm, see_memory_usage, is_model_parallel_parameter, align_dense_tensors, all_gather_dp_groups) from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.utils import logger from deepspeed.moe.utils import is_moe_param from deepspeed.git_version_info import version from deepspeed.runtime.constants import PIPE_REPLICATED from deepspeed.checkpoint.constants import (DS_VERSION, GROUP_PADDINGS, PARTITION_COUNT, SINGLE_PARTITION_OF_FP32_GROUPS, BASE_OPTIMIZER_STATE, CLIP_GRAD, ZERO_STAGE, PARAM_SLICE_MAPPINGS) from deepspeed.utils import link_hp_params from deepspeed.checkpoint import enable_universal_checkpoint def _handle_overflow(cpu_sum, x, i): import math rank = dist.get_rank() if rank == 0: t_i = -1 for v_i, v in enumerate(x.data.contiguous().view(-1)): if not math.isfinite(float(v)): t_i = v_i break logger.info( f"rank {rank} detected overflow {cpu_sum} in tensor {i}:{t_i} shape {x.shape}" )
null
10,287
import torch import os from deepspeed import comm as dist from torch._six import inf from packaging import version as pkg_version from collections import OrderedDict from deepspeed.runtime import ZeROOptimizer from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.utils import (bwc_tensor_model_parallel_rank, get_global_norm, see_memory_usage, is_model_parallel_parameter, align_dense_tensors, all_gather_dp_groups) from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.utils import logger from deepspeed.moe.utils import is_moe_param from deepspeed.git_version_info import version from deepspeed.runtime.constants import PIPE_REPLICATED from deepspeed.checkpoint.constants import (DS_VERSION, GROUP_PADDINGS, PARTITION_COUNT, SINGLE_PARTITION_OF_FP32_GROUPS, BASE_OPTIMIZER_STATE, CLIP_GRAD, ZERO_STAGE, PARAM_SLICE_MAPPINGS) from deepspeed.utils import link_hp_params from deepspeed.checkpoint import enable_universal_checkpoint def model_to_params(model): # shared params calculated only once total_params = sum( dict((p.data_ptr(), p.numel()) for p in model.parameters()).values()) return total_params def estimate_zero2_model_states_mem_needs_all_cold(total_params, num_gpus_per_node=1, num_nodes=1, additional_buffer_factor=1.5): """ Print out estimates on memory usage requirements for ZeRO 2 params, optim states and gradients for a given ``model`` and hardware setup. If it's a hypothetical model, use this function where you have to pass the ``total_params`` and ``largest_layer_params`` explicitly. If you have an actual model object, use ``estimate_zero2_model_states_mem_needs_all_live`` and everything will be derived automatically. Args: - ``total_params``: total model params - ``num_gpus_per_node``: how many gpus per node (defaults to 1) - ``num_nodes``: how many nodes (defaults to 1), - ``additional_buffer_factor``: estimation factor (defaults to 1.5): """ def format_options(cpu_offload): enabled = [] device = f'{OffloadDeviceEnum.cpu:4}' if cpu_offload else "none" enabled.append(f"offload_optimizer={device}") return ", ".join(enabled) nodes_str = "nodes" if num_nodes > 1 else "node" gpus_str = "GPUs" if num_gpus_per_node > 1 else "GPU" print( "Estimated memory needed for params, optim states and gradients for a:\n" f"HW: Setup with {num_nodes} {nodes_str}, {num_gpus_per_node} {gpus_str} per node.\n" f"SW: Model with {int(total_params/1e6)}M total params.") print(" per CPU | per GPU | Options") for cpu_offload in [True, False]: cpu_mem, gpu_mem = estimate_zero2_model_states_mem_needs( total_params=total_params, num_gpus_per_node=num_gpus_per_node, num_nodes=num_nodes, cpu_offload=cpu_offload, additional_buffer_factor=additional_buffer_factor ) options_str = format_options(cpu_offload=cpu_offload) print(f" {cpu_mem/2**30:7.2f}GB | {gpu_mem/2**30:6.2f}GB | {options_str}") The provided code snippet includes necessary dependencies for implementing the `estimate_zero2_model_states_mem_needs_all_live` function. Write a Python function `def estimate_zero2_model_states_mem_needs_all_live(model, num_gpus_per_node=1, num_nodes=1, additional_buffer_factor=1.5)` to solve the following problem: Print out estimates on memory usage requirements for ZeRO 2 params, optim states and gradients for a given ``model`` and hardware setup. If you have an actual model object, use this function and everything will be derived automatically. If it's a hypothetical model, use ``estimate_zero2_model_states_mem_needs_all_cold`` where you have to pass the ``total_params`` explicitly. Args: - ``model``: ``nn.Module`` object - ``num_gpus_per_node``: how many gpus per node (defaults to 1) - ``num_nodes``: how many nodes (defaults to 1), - ``additional_buffer_factor``: estimation factor (defaults to 1.5): Here is the function: def estimate_zero2_model_states_mem_needs_all_live(model, num_gpus_per_node=1, num_nodes=1, additional_buffer_factor=1.5): """ Print out estimates on memory usage requirements for ZeRO 2 params, optim states and gradients for a given ``model`` and hardware setup. If you have an actual model object, use this function and everything will be derived automatically. If it's a hypothetical model, use ``estimate_zero2_model_states_mem_needs_all_cold`` where you have to pass the ``total_params`` explicitly. Args: - ``model``: ``nn.Module`` object - ``num_gpus_per_node``: how many gpus per node (defaults to 1) - ``num_nodes``: how many nodes (defaults to 1), - ``additional_buffer_factor``: estimation factor (defaults to 1.5): """ total_params = model_to_params(model) estimate_zero2_model_states_mem_needs_all_cold( total_params=total_params, num_gpus_per_node=num_gpus_per_node, num_nodes=num_nodes, additional_buffer_factor=additional_buffer_factor)
Print out estimates on memory usage requirements for ZeRO 2 params, optim states and gradients for a given ``model`` and hardware setup. If you have an actual model object, use this function and everything will be derived automatically. If it's a hypothetical model, use ``estimate_zero2_model_states_mem_needs_all_cold`` where you have to pass the ``total_params`` explicitly. Args: - ``model``: ``nn.Module`` object - ``num_gpus_per_node``: how many gpus per node (defaults to 1) - ``num_nodes``: how many nodes (defaults to 1), - ``additional_buffer_factor``: estimation factor (defaults to 1.5):
10,288
import torch from deepspeed import comm as dist def print_rank_0(message): if dist.get_rank() == 0: print(message)
null
10,289
import sys import gc import collections from typing import Deque, Dict, Tuple from torch.cuda import Event, Stream from torch._six import inf from deepspeed.runtime import ZeROOptimizer from deepspeed.utils import logger from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.comm.coalesced_collectives import reduce_scatter_coalesced from deepspeed.runtime.utils import get_global_norm, is_model_parallel_parameter from deepspeed.runtime.zero.partition_parameters import * from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.parameter_offload import DeepSpeedZeRoOffload from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus from deepspeed.runtime.swap_tensor.partitioned_optimizer_swapper import PartitionedOptimizerSwapper from deepspeed.runtime.swap_tensor.pipelined_optimizer_swapper import PipelinedOptimizerSwapper from deepspeed.checkpoint.constants import OPTIMIZER_STATE_DICT, FP32_FLAT_GROUPS, PARTITION_COUNT, ZERO_STAGE def print_rank_0(message, debug=False, force=False): rank = dist.get_rank() if rank == 0 and (debug or force): print(message) # other variations # - print for all ranks w/o interleaving # printflock(f"[{rank}] {message}") # - print to log file per rank # log_rank_file(rank, message)
null
10,290
import sys import gc import collections from typing import Deque, Dict, Tuple from torch.cuda import Event, Stream from torch._six import inf from deepspeed.runtime import ZeROOptimizer from deepspeed.utils import logger from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.comm.coalesced_collectives import reduce_scatter_coalesced from deepspeed.runtime.utils import get_global_norm, is_model_parallel_parameter from deepspeed.runtime.zero.partition_parameters import * from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.parameter_offload import DeepSpeedZeRoOffload from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus from deepspeed.runtime.swap_tensor.partitioned_optimizer_swapper import PartitionedOptimizerSwapper from deepspeed.runtime.swap_tensor.pipelined_optimizer_swapper import PipelinedOptimizerSwapper from deepspeed.checkpoint.constants import OPTIMIZER_STATE_DICT, FP32_FLAT_GROUPS, PARTITION_COUNT, ZERO_STAGE def input(msg): return
null
10,291
import sys import gc import collections from typing import Deque, Dict, Tuple from torch.cuda import Event, Stream from torch._six import inf from deepspeed.runtime import ZeROOptimizer from deepspeed.utils import logger from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.comm.coalesced_collectives import reduce_scatter_coalesced from deepspeed.runtime.utils import get_global_norm, is_model_parallel_parameter from deepspeed.runtime.zero.partition_parameters import * from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.parameter_offload import DeepSpeedZeRoOffload from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus from deepspeed.runtime.swap_tensor.partitioned_optimizer_swapper import PartitionedOptimizerSwapper from deepspeed.runtime.swap_tensor.pipelined_optimizer_swapper import PipelinedOptimizerSwapper from deepspeed.checkpoint.constants import OPTIMIZER_STATE_DICT, FP32_FLAT_GROUPS, PARTITION_COUNT, ZERO_STAGE def isclose(a, b, rtol=1e-09, atol=0.0): return abs(a - b) <= max(rtol * max(abs(a), abs(b)), atol)
null
10,292
import sys import gc import collections from typing import Deque, Dict, Tuple from torch.cuda import Event, Stream from torch._six import inf from deepspeed.runtime import ZeROOptimizer from deepspeed.utils import logger from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.comm.coalesced_collectives import reduce_scatter_coalesced from deepspeed.runtime.utils import get_global_norm, is_model_parallel_parameter from deepspeed.runtime.zero.partition_parameters import * from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.parameter_offload import DeepSpeedZeRoOffload from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus from deepspeed.runtime.swap_tensor.partitioned_optimizer_swapper import PartitionedOptimizerSwapper from deepspeed.runtime.swap_tensor.pipelined_optimizer_swapper import PipelinedOptimizerSwapper from deepspeed.checkpoint.constants import OPTIMIZER_STATE_DICT, FP32_FLAT_GROUPS, PARTITION_COUNT, ZERO_STAGE def lcm(x, y): from fractions import gcd # or can import gcd from `math` in Python 3 return x * y // gcd(x, y)
null
10,293
import sys import gc import collections from typing import Deque, Dict, Tuple from torch.cuda import Event, Stream from torch._six import inf from deepspeed.runtime import ZeROOptimizer from deepspeed.utils import logger from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.comm.coalesced_collectives import reduce_scatter_coalesced from deepspeed.runtime.utils import get_global_norm, is_model_parallel_parameter from deepspeed.runtime.zero.partition_parameters import * from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.parameter_offload import DeepSpeedZeRoOffload from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus from deepspeed.runtime.swap_tensor.partitioned_optimizer_swapper import PartitionedOptimizerSwapper from deepspeed.runtime.swap_tensor.pipelined_optimizer_swapper import PipelinedOptimizerSwapper from deepspeed.checkpoint.constants import OPTIMIZER_STATE_DICT, FP32_FLAT_GROUPS, PARTITION_COUNT, ZERO_STAGE def move_to_cpu(tensor_list): for tensor in tensor_list: tensor.data = tensor.data.cpu()
null
10,294
import sys import gc import collections from typing import Deque, Dict, Tuple from torch.cuda import Event, Stream from torch._six import inf from deepspeed.runtime import ZeROOptimizer from deepspeed.utils import logger from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.comm.coalesced_collectives import reduce_scatter_coalesced from deepspeed.runtime.utils import get_global_norm, is_model_parallel_parameter from deepspeed.runtime.zero.partition_parameters import * from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.parameter_offload import DeepSpeedZeRoOffload from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus from deepspeed.runtime.swap_tensor.partitioned_optimizer_swapper import PartitionedOptimizerSwapper from deepspeed.runtime.swap_tensor.pipelined_optimizer_swapper import PipelinedOptimizerSwapper from deepspeed.checkpoint.constants import OPTIMIZER_STATE_DICT, FP32_FLAT_GROUPS, PARTITION_COUNT, ZERO_STAGE def _handle_overflow(cpu_sum, x, i): import math rank = dist.get_rank() if rank == 0: t_i = -1 for v_i, v in enumerate(x.data.contiguous().view(-1)): if not math.isfinite(float(v)): t_i = v_i break logger.info( f"rank {rank} detected overflow {cpu_sum} in tensor {i}:{t_i} shape {x.shape}" )
null
10,295
import sys import gc import collections from typing import Deque, Dict, Tuple from torch.cuda import Event, Stream from torch._six import inf from deepspeed.runtime import ZeROOptimizer from deepspeed.utils import logger from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.comm.coalesced_collectives import reduce_scatter_coalesced from deepspeed.runtime.utils import get_global_norm, is_model_parallel_parameter from deepspeed.runtime.zero.partition_parameters import * from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.parameter_offload import DeepSpeedZeRoOffload from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus from deepspeed.runtime.swap_tensor.partitioned_optimizer_swapper import PartitionedOptimizerSwapper from deepspeed.runtime.swap_tensor.pipelined_optimizer_swapper import PipelinedOptimizerSwapper from deepspeed.checkpoint.constants import OPTIMIZER_STATE_DICT, FP32_FLAT_GROUPS, PARTITION_COUNT, ZERO_STAGE def model_to_params(model): # shared params calculated only once total_params = sum( dict((p.data_ptr(), p.numel()) for p in model.parameters()).values()) largest_layer_params = 0 for m in model.modules(): # assuming no shared params within a single layer layer_params = sum(p.numel() for p in m.parameters(recurse=False)) largest_layer_params = max(largest_layer_params, layer_params) return total_params, largest_layer_params def estimate_zero3_model_states_mem_needs_all_cold(total_params, largest_layer_params, num_gpus_per_node=1, num_nodes=1, additional_buffer_factor=1.5): """ Print out estimates on memory usage requirements for ZeRO 3 params, optim states and gradients for a given ``model`` and hardware setup. If it's a hypothetical model, use this function where you have to pass the ``total_params`` and ``largest_layer_params`` explicitly. If you have an actual model object, use ``estimate_zero3_model_states_mem_needs_all_live`` and everything will be derived automatically. Args: - ``total_params``: total model params - ``largest_layer_params``: largest layer's params - ``num_gpus_per_node``: how many gpus per node (defaults to 1) - ``num_nodes``: how many nodes (defaults to 1), - ``additional_buffer_factor``: estimation factor (defaults to 1.5): """ def format_options(cpu_offload, cpu_offload_params, zero_init): enabled = [] padded_cpu_str = f'{OffloadDeviceEnum.cpu:4}' param_device = padded_cpu_str if cpu_offload_params else "none" enabled.append(f"offload_param={param_device}") optimizer_device = padded_cpu_str if cpu_offload else "none" enabled.append(f"offload_optimizer={optimizer_device}") enabled.append(f"zero_init={1 if zero_init else 0}") return ", ".join(enabled) nodes_str = "nodes" if num_nodes > 1 else "node" gpus_str = "GPUs" if num_gpus_per_node > 1 else "GPU" print( "Estimated memory needed for params, optim states and gradients for a:\n" f"HW: Setup with {num_nodes} {nodes_str}, {num_gpus_per_node} {gpus_str} per node.\n" f"SW: Model with {int(total_params/1e6)}M total params, {int(largest_layer_params/1e6)}M largest layer params." ) print(" per CPU | per GPU | Options") for cpu_offload in [True, False]: for cpu_offload_params in [True, False]: if not cpu_offload and cpu_offload_params: continue for zero_init in [True, False]: cpu_mem, gpu_mem, largest_layer_memory = estimate_zero3_model_states_mem_needs( total_params=total_params, largest_layer_params=largest_layer_params, num_gpus_per_node=num_gpus_per_node, num_nodes=num_nodes, cpu_offload=cpu_offload, cpu_offload_params=cpu_offload_params, zero_init=zero_init, additional_buffer_factor=additional_buffer_factor ) options_str = format_options(cpu_offload=cpu_offload, cpu_offload_params=cpu_offload_params, zero_init=zero_init) print( f" {cpu_mem/2**30:7.2f}GB | {gpu_mem/2**30:6.2f}GB | {options_str}") The provided code snippet includes necessary dependencies for implementing the `estimate_zero3_model_states_mem_needs_all_live` function. Write a Python function `def estimate_zero3_model_states_mem_needs_all_live(model, num_gpus_per_node=1, num_nodes=1, additional_buffer_factor=1.5)` to solve the following problem: Print out estimates on memory usage requirements for ZeRO 3 params, optim states and gradients for a given ``model`` and hardware setup. If you have an actual model object, use this function and everything will be derived automatically. If it's a hypothetical model, use ``estimate_zero3_model_states_mem_needs_all_cold`` where you have to pass the ``total_params`` and ``largest_layer_params`` explicitly. Args: - ``model``: ``nn.Module`` object - ``num_gpus_per_node``: how many gpus per node (defaults to 1) - ``num_nodes``: how many nodes (defaults to 1), - ``additional_buffer_factor``: estimation factor (defaults to 1.5): Here is the function: def estimate_zero3_model_states_mem_needs_all_live(model, num_gpus_per_node=1, num_nodes=1, additional_buffer_factor=1.5): """ Print out estimates on memory usage requirements for ZeRO 3 params, optim states and gradients for a given ``model`` and hardware setup. If you have an actual model object, use this function and everything will be derived automatically. If it's a hypothetical model, use ``estimate_zero3_model_states_mem_needs_all_cold`` where you have to pass the ``total_params`` and ``largest_layer_params`` explicitly. Args: - ``model``: ``nn.Module`` object - ``num_gpus_per_node``: how many gpus per node (defaults to 1) - ``num_nodes``: how many nodes (defaults to 1), - ``additional_buffer_factor``: estimation factor (defaults to 1.5): """ total_params, largest_layer_params = model_to_params(model) estimate_zero3_model_states_mem_needs_all_cold( total_params=total_params, largest_layer_params=largest_layer_params, num_gpus_per_node=num_gpus_per_node, num_nodes=num_nodes, additional_buffer_factor=additional_buffer_factor)
Print out estimates on memory usage requirements for ZeRO 3 params, optim states and gradients for a given ``model`` and hardware setup. If you have an actual model object, use this function and everything will be derived automatically. If it's a hypothetical model, use ``estimate_zero3_model_states_mem_needs_all_cold`` where you have to pass the ``total_params`` and ``largest_layer_params`` explicitly. Args: - ``model``: ``nn.Module`` object - ``num_gpus_per_node``: how many gpus per node (defaults to 1) - ``num_nodes``: how many nodes (defaults to 1), - ``additional_buffer_factor``: estimation factor (defaults to 1.5):
10,296
from pydantic import Field, validator import sys from typing import Optional from enum import Enum from deepspeed.runtime.config_utils import get_scalar_param, pp_int, DeepSpeedConfigModel from deepspeed.utils import logger from .offload_config import DeepSpeedZeroOffloadParamConfig, DeepSpeedZeroOffloadOptimizerConfig, OffloadDeviceEnum ZERO_OPTIMIZATION = "zero_optimization" def read_zero_config_deprecated(param_dict): class DeepSpeedZeroConfig(DeepSpeedConfigModel): def overlap_comm_valid(cls, field_value, values): def get_zero_config(param_dict): if ZERO_OPTIMIZATION in param_dict: zero_config_dict = param_dict[ZERO_OPTIMIZATION] if isinstance(zero_config_dict, bool): zero_config_dict = read_zero_config_deprecated(param_dict) else: zero_config_dict = {} return DeepSpeedZeroConfig(**zero_config_dict)
null
10,297
import sys import torch from torch.cuda import Stream from collections import OrderedDict from deepspeed.runtime.utils import see_memory_usage from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.partition_parameters import _init_external_params from deepspeed.runtime.zero.partition_parameters import * from deepspeed.runtime.zero.partitioned_param_coordinator import PartitionedParameterCoordinator, iter_params from deepspeed import comm as dist def is_builtin_type(obj): warned = False def _apply_to_tensors_only(module, functional, backward_function, outputs): if isinstance(outputs, (tuple, list)): touched_outputs = [] for output in outputs: touched_output = _apply_to_tensors_only(module, functional, backward_function, output) touched_outputs.append(touched_output) return outputs.__class__(touched_outputs) elif isinstance(outputs, dict): # apply inplace to avoid recreating dict inherited objects for key in outputs.keys(): outputs[key] = _apply_to_tensors_only(module, functional, backward_function, outputs[key]) return outputs elif type(outputs) is torch.Tensor: return functional.apply(module, backward_function, outputs) else: if not is_builtin_type(outputs): global warned if not warned and dist.get_rank() == 0: logger.warning( f"A module has unknown inputs or outputs type ({type(outputs)}) and the tensors embedded in it cannot be detected. " "The ZeRO-3 hooks designed to trigger before or after backward pass of the module relies on knowing the input and " "output tensors and therefore may not get triggered properly.") warned = True return outputs
null
10,298
import sys import torch from torch.cuda import Stream from collections import OrderedDict from deepspeed.runtime.utils import see_memory_usage from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.partition_parameters import _init_external_params from deepspeed.runtime.zero.partition_parameters import * from deepspeed.runtime.zero.partitioned_param_coordinator import PartitionedParameterCoordinator, iter_params from deepspeed import comm as dist def _apply_forward_and_backward_to_tensors_only(module, forward_function, backward_function, outputs): if type(outputs) is tuple: touched_outputs = [] for output in outputs: touched_output = _apply_forward_and_backward_to_tensors_only( module, forward_function, backward_function, output) touched_outputs.append(touched_output) return tuple(touched_outputs) elif type(outputs) is torch.Tensor: forward_function(outputs) if outputs.requires_grad: outputs.register_hook(backward_function) return outputs else: return outputs
null
10,299
import sys import torch from torch.cuda import Stream from collections import OrderedDict from deepspeed.runtime.utils import see_memory_usage from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.partition_parameters import _init_external_params from deepspeed.runtime.zero.partition_parameters import * from deepspeed.runtime.zero.partitioned_param_coordinator import PartitionedParameterCoordinator, iter_params from deepspeed import comm as dist class ZeROOrderedDict(OrderedDict): def __init__(self, parent_module, *args, **kwargs): """A replacement for ``collections.OrderedDict`` to detect external ZeRO params. Args: parent_module (``collections.OrderedDict``): the collection to replace """ super().__init__(*args, **kwargs) self._parent_module = parent_module self._in_forward = False def __getitem__(self, key): param = super().__getitem__(key) # Params can be registered as None (e.g., bias) if param is None: return param if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: if self._parent_module._parameters._in_forward: register_external_parameter(FWD_MODULE_STACK[-1], param) param.all_gather() print_rank_0( f'Registering external parameter from getter {key} ds_id = {param.ds_id}', force=False) return param def _inject_parameters(module, cls): for module in module.modules(): if cls == ZeROOrderedDict: new_param = cls(parent_module=module) else: new_param = cls() for key, param in module._parameters.items(): new_param[key] = param module._parameters = new_param
null
10,300
import math import os import types from typing import Callable, Iterable from enum import Enum import functools import itertools from typing import List import torch from torch import Tensor from deepspeed import comm as dist from torch.nn import Module from torch.nn import Parameter from .linear import zero3_linear_wrap import deepspeed from ..utils import get_only_unique_item, see_memory_usage from deepspeed.runtime.zero.utils import assert_ints_same_as_other_ranks from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.utils import instrument_w_nvtx, logger from deepspeed.comm.comm import init_distributed from deepspeed.utils.debug import (debug_param2name_id_shape, debug_param2name_id_shape_device, debug_module2name, debug_param2name_id, debug_param2name_id_shape_status) from ..swap_tensor.partitioned_param_swapper import AsyncPartitionedParameterSwapper, PartitionedParamStatus def _dist_allgather_fn(input_tensor: Tensor, output_tensor: Tensor, group=None): return instrument_w_nvtx(dist.allgather_fn)(output_tensor, input_tensor, group=group, async_op=True)
null
10,301
import math import os import types from typing import Callable, Iterable from enum import Enum import functools import itertools from typing import List import torch from torch import Tensor from deepspeed import comm as dist from torch.nn import Module from torch.nn import Parameter from .linear import zero3_linear_wrap import deepspeed from ..utils import get_only_unique_item, see_memory_usage from deepspeed.runtime.zero.utils import assert_ints_same_as_other_ranks from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.utils import instrument_w_nvtx, logger from deepspeed.comm.comm import init_distributed from deepspeed.utils.debug import (debug_param2name_id_shape, debug_param2name_id_shape_device, debug_module2name, debug_param2name_id, debug_param2name_id_shape_status) from ..swap_tensor.partitioned_param_swapper import AsyncPartitionedParameterSwapper, PartitionedParamStatus def print_rank_0(message, debug=False, force=False): rank = dist.get_rank() if rank == 0 and (debug or force): print(message) # other variations # - print for all ranks w/o interleaving # printflock(f"[{rank}] {message}") # - print to log file per rank # log_rank_file(rank, message)
null
10,302
import math import os import types from typing import Callable, Iterable from enum import Enum import functools import itertools from typing import List import torch from torch import Tensor from deepspeed import comm as dist from torch.nn import Module from torch.nn import Parameter from .linear import zero3_linear_wrap import deepspeed from ..utils import get_only_unique_item, see_memory_usage from deepspeed.runtime.zero.utils import assert_ints_same_as_other_ranks from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.utils import instrument_w_nvtx, logger from deepspeed.comm.comm import init_distributed from deepspeed.utils.debug import (debug_param2name_id_shape, debug_param2name_id_shape_device, debug_module2name, debug_param2name_id, debug_param2name_id_shape_status) from ..swap_tensor.partitioned_param_swapper import AsyncPartitionedParameterSwapper, PartitionedParamStatus def debug_rank0(msg: str) -> None: if dist.get_rank() == 0: logger.debug(msg)
null
10,303
import math import os import types from typing import Callable, Iterable from enum import Enum import functools import itertools from typing import List import torch from torch import Tensor from deepspeed import comm as dist from torch.nn import Module from torch.nn import Parameter from .linear import zero3_linear_wrap import deepspeed from ..utils import get_only_unique_item, see_memory_usage from deepspeed.runtime.zero.utils import assert_ints_same_as_other_ranks from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.utils import instrument_w_nvtx, logger from deepspeed.comm.comm import init_distributed from deepspeed.utils.debug import (debug_param2name_id_shape, debug_param2name_id_shape_device, debug_module2name, debug_param2name_id, debug_param2name_id_shape_status) from ..swap_tensor.partitioned_param_swapper import AsyncPartitionedParameterSwapper, PartitionedParamStatus def is_zero_param(parameter): if not torch.is_tensor(parameter): return False return hasattr(parameter, 'ds_id')
null
10,304
import math import os import types from typing import Callable, Iterable from enum import Enum import functools import itertools from typing import List import torch from torch import Tensor from deepspeed import comm as dist from torch.nn import Module from torch.nn import Parameter from .linear import zero3_linear_wrap import deepspeed from ..utils import get_only_unique_item, see_memory_usage from deepspeed.runtime.zero.utils import assert_ints_same_as_other_ranks from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.utils import instrument_w_nvtx, logger from deepspeed.comm.comm import init_distributed from deepspeed.utils.debug import (debug_param2name_id_shape, debug_param2name_id_shape_device, debug_module2name, debug_param2name_id, debug_param2name_id_shape_status) from ..swap_tensor.partitioned_param_swapper import AsyncPartitionedParameterSwapper, PartitionedParamStatus def _init_external_params(module): if not hasattr(module, '_external_params'): module._external_params = {} def external_parameters(self): return self._external_params.items() def all_parameters(self): return itertools.chain(self.named_parameters(self, recurse=False), external_parameters(self)) module.ds_external_parameters = types.MethodType(external_parameters, module) module.all_parameters = types.MethodType(all_parameters, module) The provided code snippet includes necessary dependencies for implementing the `register_external_parameter` function. Write a Python function `def register_external_parameter(module, parameter)` to solve the following problem: Instruct DeepSpeed to coordinate ``parameter``'s collection and partitioning in the forward and backward passes of ``module``. This is used when a parameter is accessed outside of its owning module's ``forward()``. DeepSpeed must know to collect it from its partitioned state and when to release the memory. .. note:: This is only applicable to training with ZeRO stage 3. Args: module (``torch.nn.Module``): The module that requires ``parameter`` in its forward pass. parameter (``torch.nn.Parameter``): The parameter to register. Raises: RuntimeError: If ``parameter`` is not of type ``torch.nn.Parameter``. Examples ======== #. Register a weight that is used in another module's forward pass (line 6). Parameter ``layer1.weight`` is used by ``layer2`` (line 11). .. code-block:: python :linenos: :emphasize-lines: 6,11 class ModuleZ3(torch.nn.Module): def __init__(self, *args): super().__init__(self, *args) self.layer1 = SomeLayer() self.layer2 = OtherLayer() deepspeed.zero.register_external_parameter(self, self.layer1.weight) def forward(self, input): x = self.layer1(input) # self.layer1.weight is required by self.layer2.forward y = self.layer2(x, self.layer1.weight) return y Here is the function: def register_external_parameter(module, parameter): """Instruct DeepSpeed to coordinate ``parameter``'s collection and partitioning in the forward and backward passes of ``module``. This is used when a parameter is accessed outside of its owning module's ``forward()``. DeepSpeed must know to collect it from its partitioned state and when to release the memory. .. note:: This is only applicable to training with ZeRO stage 3. Args: module (``torch.nn.Module``): The module that requires ``parameter`` in its forward pass. parameter (``torch.nn.Parameter``): The parameter to register. Raises: RuntimeError: If ``parameter`` is not of type ``torch.nn.Parameter``. Examples ======== #. Register a weight that is used in another module's forward pass (line 6). Parameter ``layer1.weight`` is used by ``layer2`` (line 11). .. code-block:: python :linenos: :emphasize-lines: 6,11 class ModuleZ3(torch.nn.Module): def __init__(self, *args): super().__init__(self, *args) self.layer1 = SomeLayer() self.layer2 = OtherLayer() deepspeed.zero.register_external_parameter(self, self.layer1.weight) def forward(self, input): x = self.layer1(input) # self.layer1.weight is required by self.layer2.forward y = self.layer2(x, self.layer1.weight) return y """ if not isinstance(parameter, torch.nn.Parameter): raise RuntimeError('Parameter is not a torch.nn.Parameter') if not hasattr(module, '_external_params'): _init_external_params(module) key = id(parameter) module._external_params[key] = parameter
Instruct DeepSpeed to coordinate ``parameter``'s collection and partitioning in the forward and backward passes of ``module``. This is used when a parameter is accessed outside of its owning module's ``forward()``. DeepSpeed must know to collect it from its partitioned state and when to release the memory. .. note:: This is only applicable to training with ZeRO stage 3. Args: module (``torch.nn.Module``): The module that requires ``parameter`` in its forward pass. parameter (``torch.nn.Parameter``): The parameter to register. Raises: RuntimeError: If ``parameter`` is not of type ``torch.nn.Parameter``. Examples ======== #. Register a weight that is used in another module's forward pass (line 6). Parameter ``layer1.weight`` is used by ``layer2`` (line 11). .. code-block:: python :linenos: :emphasize-lines: 6,11 class ModuleZ3(torch.nn.Module): def __init__(self, *args): super().__init__(self, *args) self.layer1 = SomeLayer() self.layer2 = OtherLayer() deepspeed.zero.register_external_parameter(self, self.layer1.weight) def forward(self, input): x = self.layer1(input) # self.layer1.weight is required by self.layer2.forward y = self.layer2(x, self.layer1.weight) return y
10,305
import math import os import types from typing import Callable, Iterable from enum import Enum import functools import itertools from typing import List import torch from torch import Tensor from deepspeed import comm as dist from torch.nn import Module from torch.nn import Parameter from .linear import zero3_linear_wrap import deepspeed from ..utils import get_only_unique_item, see_memory_usage from deepspeed.runtime.zero.utils import assert_ints_same_as_other_ranks from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.utils import instrument_w_nvtx, logger from deepspeed.comm.comm import init_distributed from deepspeed.utils.debug import (debug_param2name_id_shape, debug_param2name_id_shape_device, debug_module2name, debug_param2name_id, debug_param2name_id_shape_status) from ..swap_tensor.partitioned_param_swapper import AsyncPartitionedParameterSwapper, PartitionedParamStatus The provided code snippet includes necessary dependencies for implementing the `unregister_external_parameter` function. Write a Python function `def unregister_external_parameter(module, parameter)` to solve the following problem: Reverses the effects of :meth:`register_external_parameter`. Args: module (``torch.nn.Module``): The module to affect. parameter (``torch.nn.Parameter``): The parameter to unregister. Raises: RuntimeError: If ``parameter`` is not of type ``torch.nn.Parameter``. RuntimeError: If ``parameter`` is not a registered external parameter of ``module``. Here is the function: def unregister_external_parameter(module, parameter): """Reverses the effects of :meth:`register_external_parameter`. Args: module (``torch.nn.Module``): The module to affect. parameter (``torch.nn.Parameter``): The parameter to unregister. Raises: RuntimeError: If ``parameter`` is not of type ``torch.nn.Parameter``. RuntimeError: If ``parameter`` is not a registered external parameter of ``module``. """ if not isinstance(parameter, torch.nn.Parameter): raise RuntimeError('Parameter is not a torch.nn.Parameter') if not hasattr(module, '_external_params') or id(parameter) not in module._external_params: raise RuntimeError('Parameter is not a registered external parameter of module.') key = id(parameter) del module._external_params[key]
Reverses the effects of :meth:`register_external_parameter`. Args: module (``torch.nn.Module``): The module to affect. parameter (``torch.nn.Parameter``): The parameter to unregister. Raises: RuntimeError: If ``parameter`` is not of type ``torch.nn.Parameter``. RuntimeError: If ``parameter`` is not a registered external parameter of ``module``.
10,306
import math import os import types from typing import Callable, Iterable from enum import Enum import functools import itertools from typing import List import torch from torch import Tensor from deepspeed import comm as dist from torch.nn import Module from torch.nn import Parameter from .linear import zero3_linear_wrap import deepspeed from ..utils import get_only_unique_item, see_memory_usage from deepspeed.runtime.zero.utils import assert_ints_same_as_other_ranks from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.utils import instrument_w_nvtx, logger from deepspeed.comm.comm import init_distributed from deepspeed.utils.debug import (debug_param2name_id_shape, debug_param2name_id_shape_device, debug_module2name, debug_param2name_id, debug_param2name_id_shape_status) from ..swap_tensor.partitioned_param_swapper import AsyncPartitionedParameterSwapper, PartitionedParamStatus def zero_wrapper_for_fp_tensor_constructor(fn: Callable, target_fp_dtype: torch.dtype) -> Callable: def wrapped_fn(*args, **kwargs) -> Tensor: if kwargs.get("device", None) is None: kwargs['device'] = torch.device('cuda:{}'.format(os.environ["LOCAL_RANK"])) tensor: Tensor = fn(*args, **kwargs) if tensor.is_floating_point(): tensor = tensor.to(target_fp_dtype) return tensor return wrapped_fn
null
10,307
import math import os import types from typing import Callable, Iterable from enum import Enum import functools import itertools from typing import List import torch from torch import Tensor from deepspeed import comm as dist from torch.nn import Module from torch.nn import Parameter from .linear import zero3_linear_wrap import deepspeed from ..utils import get_only_unique_item, see_memory_usage from deepspeed.runtime.zero.utils import assert_ints_same_as_other_ranks from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.utils import instrument_w_nvtx, logger from deepspeed.comm.comm import init_distributed from deepspeed.utils.debug import (debug_param2name_id_shape, debug_param2name_id_shape_device, debug_module2name, debug_param2name_id, debug_param2name_id_shape_status) from ..swap_tensor.partitioned_param_swapper import AsyncPartitionedParameterSwapper, PartitionedParamStatus _orig_torch_empty = torch.empty def get_new_tensor_fn_for_dtype(dtype: torch.dtype) -> Callable: def new_tensor(cls, *args) -> Tensor: device = torch.device('cuda:{}'.format(os.environ["LOCAL_RANK"])) tensor = _orig_torch_empty(0, device=device).new_empty(*args) if tensor.is_floating_point(): tensor = tensor.to(dtype) return tensor return new_tensor
null
10,308
import math import os import types from typing import Callable, Iterable from enum import Enum import functools import itertools from typing import List import torch from torch import Tensor from deepspeed import comm as dist from torch.nn import Module from torch.nn import Parameter from .linear import zero3_linear_wrap import deepspeed from ..utils import get_only_unique_item, see_memory_usage from deepspeed.runtime.zero.utils import assert_ints_same_as_other_ranks from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.utils import instrument_w_nvtx, logger from deepspeed.comm.comm import init_distributed from deepspeed.utils.debug import (debug_param2name_id_shape, debug_param2name_id_shape_device, debug_module2name, debug_param2name_id, debug_param2name_id_shape_status) from ..swap_tensor.partitioned_param_swapper import AsyncPartitionedParameterSwapper, PartitionedParamStatus class ZeroParamStatus(Enum): # parameters are fully present and ready for use on all processes AVAILABLE = 1 # parameters are either partitioned or remote in some or all process NOT_AVAILABLE = 2 # parameters are being gathered. INFLIGHT = 3 The provided code snippet includes necessary dependencies for implementing the `free_param` function. Write a Python function `def free_param(param: Parameter) -> None` to solve the following problem: Free underlying storage of a parameter. Here is the function: def free_param(param: Parameter) -> None: """Free underlying storage of a parameter.""" assert not param.ds_active_sub_modules, param.ds_summary() if param.data.is_cuda: # need to make sure that we don't free the parameter while it is still # being used for computation param.data.record_stream(torch.cuda.current_stream()) # param.data doesn't store anything meaningful in partitioned state param.data = torch.empty(0, dtype=param.dtype, device=param.device) param.ds_status = ZeroParamStatus.NOT_AVAILABLE
Free underlying storage of a parameter.
10,309
import math import os import types from typing import Callable, Iterable from enum import Enum import functools import itertools from typing import List import torch from torch import Tensor from deepspeed import comm as dist from torch.nn import Module from torch.nn import Parameter from .linear import zero3_linear_wrap import deepspeed from ..utils import get_only_unique_item, see_memory_usage from deepspeed.runtime.zero.utils import assert_ints_same_as_other_ranks from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.utils import instrument_w_nvtx, logger from deepspeed.comm.comm import init_distributed from deepspeed.utils.debug import (debug_param2name_id_shape, debug_param2name_id_shape_device, debug_module2name, debug_param2name_id, debug_param2name_id_shape_status) from ..swap_tensor.partitioned_param_swapper import AsyncPartitionedParameterSwapper, PartitionedParamStatus zero_init_enabled = False _orig_torch_empty = torch.empty _orig_torch_zeros = torch.zeros _orig_torch_ones = torch.ones _orig_torch_full = torch.full def get_all_subclasses(cls): subclass_list = [] def recurse(cl): for subclass in cl.__subclasses__(): subclass_list.append(subclass) recurse(subclass) recurse(cls) return set(subclass_list) def shutdown_init_context(): global zero_init_enabled if not zero_init_enabled: return def _disable_class(cls): cls.__init__ = cls._old_init # Replace .__init__() for all existing subclasses of torch.nn.Module for subclass in get_all_subclasses(torch.nn.modules.module.Module): _disable_class(subclass) # putting methods back the way we found them torch.nn.modules.module.Module.__init_subclass__ = torch.nn.modules.module.Module._old_init_subclass torch.nn.modules.module.Module.apply = torch.nn.modules.module.Module._old_apply torch.Tensor.__new__ = torch.Tensor.__old_new__ torch.empty = _orig_torch_empty torch.zeros = _orig_torch_zeros torch.ones = _orig_torch_ones torch.full = _orig_torch_full # un doing it here will undo it during training # if self.mem_efficient_linear: # torch.nn.functional.linear = self.linear_bk # if self.mem_efficient_linear: # torch.nn.functional.linear = self.linear_bk zero_init_enabled = False
null
10,310
import torch import deepspeed from deepspeed.runtime.utils import partition_uniform as partition The provided code snippet includes necessary dependencies for implementing the `split_tensor_along_last_dim` function. Write a Python function `def split_tensor_along_last_dim(tensor, partitions, contiguous_split_chunks=False)` to solve the following problem: Split a tensor along its last dimension. Adapted from Megatron-LM. Arguments: tensor: input tensor. partitions: list of partition sizes to supply to torch.split contiguous_split_chunks: If True, make each chunk contiguous in memory. Here is the function: def split_tensor_along_last_dim(tensor, partitions, contiguous_split_chunks=False): """Split a tensor along its last dimension. Adapted from Megatron-LM. Arguments: tensor: input tensor. partitions: list of partition sizes to supply to torch.split contiguous_split_chunks: If True, make each chunk contiguous in memory. """ # Get the size and dimension. last_dim = tensor.dim() - 1 # Split. tensor_list = torch.split(tensor, partitions, dim=last_dim) # Note: torch.split does not create contiguous tensors by default. if contiguous_split_chunks: return tuple(chunk.contiguous() for chunk in tensor_list) return tensor_list
Split a tensor along its last dimension. Adapted from Megatron-LM. Arguments: tensor: input tensor. partitions: list of partition sizes to supply to torch.split contiguous_split_chunks: If True, make each chunk contiguous in memory.
10,311
import math import torch from torch import Tensor from torch.nn.parameter import Parameter from torch.nn import init from torch.nn.modules.module import Module from deepspeed.runtime.utils import noop_decorator from deepspeed import comm as dist def print_rank_0(message, debug=False, force=False): if dist.get_rank() == 0 and (debug or force): print(message)
null
10,312
import math import torch from torch import Tensor from torch.nn.parameter import Parameter from torch.nn import init from torch.nn.modules.module import Module from deepspeed.runtime.utils import noop_decorator from deepspeed import comm as dist class LinearFunctionForZeroStage3(torch.autograd.Function): def forward(ctx, input, weight, bias=None): def backward(ctx, grad_output): def zero3_linear_wrap(input, weight, bias=None): if bias is None: return LinearFunctionForZeroStage3.apply(input, weight) else: return LinearFunctionForZeroStage3.apply(input, weight, bias)
null
10,313
def to_python_float(t): if hasattr(t, 'item'): return t.item() return t[0]
null
10,314
import torch from deepspeed.utils.logging import logger from deepspeed import comm as dist def swap_in_tensors(swap_handle, tensor_buffers, swap_paths): for buffer, path in zip(tensor_buffers, swap_paths): assert (swap_handle.async_pread(buffer, path) == 0)
null
10,315
import torch from deepspeed.utils.logging import logger from deepspeed import comm as dist def swap_out_tensors(swap_handle, tensor_buffers, swap_paths): for buffer, path in zip(tensor_buffers, swap_paths): assert (swap_handle.async_pwrite(buffer, path) == 0)
null
10,316
import torch from deepspeed.utils.logging import logger from deepspeed import comm as dist logger = LoggerFactory.create_logger(name="DeepSpeed", level=logging.INFO) def print_object(obj, name, exclude_list=[]): logger.info('{}:'.format(name)) for arg in sorted(vars(obj)): if not arg in exclude_list: dots = '.' * (29 - len(arg)) logger.info(' {} {} {}'.format(arg, dots, getattr(obj, arg)))
null
10,317
import torch from deepspeed.utils.logging import logger from deepspeed import comm as dist def get_sized_buffer(buffer, num_elems): assert num_elems <= buffer.numel(), \ f'num_elems {num_elems} > buffer {buffer.numel()}' return buffer.narrow(0, 0, num_elems) if num_elems < buffer.numel() else buffer def get_sized_buffers(buffer_list, num_elems_list): swap_buffers = [ get_sized_buffer(buffer, num_elems) \ for buffer, num_elems in zip(buffer_list, num_elems_list) ] return swap_buffers
null
10,318
from deepspeed.runtime.config_utils import get_scalar_param from deepspeed.runtime.swap_tensor.constants import * AIO_DEFAULT_DICT = { AIO_BLOCK_SIZE: AIO_BLOCK_SIZE_DEFAULT, AIO_QUEUE_DEPTH: AIO_QUEUE_DEPTH_DEFAULT, AIO_THREAD_COUNT: AIO_THREAD_COUNT_DEFAULT, AIO_SINGLE_SUBMIT: AIO_SINGLE_SUBMIT_DEFAULT, AIO_OVERLAP_EVENTS: AIO_OVERLAP_EVENTS_DEFAULT } def get_scalar_param(param_dict, param_name, param_default_value): return param_dict.get(param_name, param_default_value) def get_aio_config(param_dict): if AIO in param_dict.keys() and param_dict[AIO] is not None: aio_dict = param_dict[AIO] return { AIO_BLOCK_SIZE: get_scalar_param(aio_dict, AIO_BLOCK_SIZE, AIO_BLOCK_SIZE_DEFAULT), AIO_QUEUE_DEPTH: get_scalar_param(aio_dict, AIO_QUEUE_DEPTH, AIO_QUEUE_DEPTH_DEFAULT), AIO_THREAD_COUNT: get_scalar_param(aio_dict, AIO_THREAD_COUNT, AIO_THREAD_COUNT_DEFAULT), AIO_SINGLE_SUBMIT: get_scalar_param(aio_dict, AIO_SINGLE_SUBMIT, AIO_SINGLE_SUBMIT_DEFAULT), AIO_OVERLAP_EVENTS: get_scalar_param(aio_dict, AIO_OVERLAP_EVENTS, AIO_OVERLAP_EVENTS_DEFAULT) } return AIO_DEFAULT_DICT
null
10,319
import os import shutil from enum import Enum import torch from deepspeed import comm as dist from deepspeed.ops.aio import AsyncIOBuilder from .constants import * from .utils import swap_in_tensors, swap_out_tensors, MIN_AIO_BYTES, AIO_ALIGNED_BYTES, print_object, SwapBufferPool def print_rank_0(message, debug=False, force=False): if dist.get_rank() == 0 and (debug or force): print(message)
null
10,320
import pickle import typing import torch from deepspeed import comm as dist from packaging.version import Version from deepspeed.git_version_info import torch_info _groups = None _grid = None def can_send_recv() -> bool: torch_version = Version(torch_info['version']) sendrecv_min = Version('1.8') return torch_version >= sendrecv_min def init_process_groups(grid): global _groups, _grid _grid = grid assert _grid.pipe_parallel_size > 1, "There is no pipeline parallelism" if not can_send_recv(): _groups = [dist.new_group(ranks=group) for group in _grid.p2p_groups]
null
10,321
import pickle import typing import torch from deepspeed import comm as dist from packaging.version import Version from deepspeed.git_version_info import torch_info _async = [] def wait(): global _async for op in _async: op.wait() _async = [] torch.cuda.synchronize()
null
10,322
import pickle import typing import torch from deepspeed import comm as dist from packaging.version import Version from deepspeed.git_version_info import torch_info def send(tensor, dest_stage, async_op=False): global _groups assert async_op == False, "Doesn't support async_op true" src_stage = _grid.get_stage_id() _is_valid_send_recv(src_stage, dest_stage) dest_rank = _grid.stage_to_global(stage_id=dest_stage) if async_op: global _async op = dist.isend(tensor, dest_rank) _async.append(op) else: if can_send_recv(): return dist.send(tensor, dest_rank) else: group = _get_send_recv_group(src_stage, dest_stage) src_rank = _grid.stage_to_global(stage_id=src_stage) return dist.broadcast(tensor, src_rank, group=group, async_op=async_op) The provided code snippet includes necessary dependencies for implementing the `send_obj` function. Write a Python function `def send_obj(msg: typing.Any, dest: int)` to solve the following problem: Send an arbitrary python object to ``dest``. Note: ``msg`` must be pickleable. WARN: This incurs a CPU -> GPU transfer and should be used sparingly for performance reasons. Args: msg (typing.Any): The object to send. dest (int): Destination rank. Here is the function: def send_obj(msg: typing.Any, dest: int): """Send an arbitrary python object to ``dest``. Note: ``msg`` must be pickleable. WARN: This incurs a CPU -> GPU transfer and should be used sparingly for performance reasons. Args: msg (typing.Any): The object to send. dest (int): Destination rank. """ # serialize the message msg = pickle.dumps(msg) # construct a tensor to send msg = torch.ByteTensor(torch.ByteStorage.from_buffer(msg)).cuda() # Send meta and message length_tensor = torch.tensor([len(msg)], dtype=torch.long).cuda() dist.send(length_tensor, dst=dest) dist.send(msg, dst=dest)
Send an arbitrary python object to ``dest``. Note: ``msg`` must be pickleable. WARN: This incurs a CPU -> GPU transfer and should be used sparingly for performance reasons. Args: msg (typing.Any): The object to send. dest (int): Destination rank.
10,323
import pickle import typing import torch from deepspeed import comm as dist from packaging.version import Version from deepspeed.git_version_info import torch_info def recv(tensor, src_stage, async_op=False): global _groups assert async_op == False, "Doesn't support async_op true" dest_stage = _grid.get_stage_id() _is_valid_send_recv(src_stage, dest_stage) src_rank = _grid.stage_to_global(stage_id=src_stage) if async_op: global _async op = dist.irecv(tensor, src_rank) _async.append(op) else: if can_send_recv(): return dist.recv(tensor, src_rank) else: group = _get_send_recv_group(src_stage, dest_stage) return dist.broadcast(tensor, src_rank, group=group, async_op=async_op) The provided code snippet includes necessary dependencies for implementing the `recv_obj` function. Write a Python function `def recv_obj(sender: int) -> typing.Any` to solve the following problem: Receive an arbitrary python object from ``sender``. WARN: This incur a CPU <-> GPU transfers and should be used sparingly for performance reasons. Args: sender (int): The rank sending the message. Here is the function: def recv_obj(sender: int) -> typing.Any: """Receive an arbitrary python object from ``sender``. WARN: This incur a CPU <-> GPU transfers and should be used sparingly for performance reasons. Args: sender (int): The rank sending the message. """ # Get message meta length = torch.tensor([0], dtype=torch.long).cuda() dist.recv(length, src=sender) # Receive and deserialize msg = torch.empty(length.item(), dtype=torch.uint8).cuda() dist.recv(msg, src=sender) msg = pickle.loads(msg.cpu().numpy().tobytes()) def _to(x): """Recursively move to the current device.""" if torch.is_tensor(x): return x.cuda() if isinstance(x, (tuple, list)): ret = [_to(x_) for x_ in x] if isinstance(x, tuple): ret = tuple(ret) return ret # handle kwargs if isinstance(x, dict): ret = dict() for key, val in x.items(): ret[_to(key)] = _to(val) return ret # Anything else is a no-op return x msg = _to(msg) return msg
Receive an arbitrary python object from ``sender``. WARN: This incur a CPU <-> GPU transfers and should be used sparingly for performance reasons. Args: sender (int): The rank sending the message.
10,324
from ..utils import call_to_str from abc import ABC, abstractmethod def _is_even(x): return x % 2 == 0
null
10,325
from ..utils import call_to_str from abc import ABC, abstractmethod def _is_odd(x): return x % 2 != 0
null
10,326
from deepspeed import comm as dist from collections import namedtuple from itertools import product as cartesian_product The provided code snippet includes necessary dependencies for implementing the `_prime_factors` function. Write a Python function `def _prime_factors(N)` to solve the following problem: Returns the prime factorization of positive integer N. Here is the function: def _prime_factors(N): """ Returns the prime factorization of positive integer N. """ if N <= 0: raise ValueError("Values must be strictly positive.") primes = [] while N != 1: for candidate in range(2, N + 1): if N % candidate == 0: primes.append(candidate) N //= candidate break return primes
Returns the prime factorization of positive integer N.
10,327
from types import MethodType import torch from deepspeed import comm as dist from deepspeed.utils import logger from deepspeed.utils.timer import ThroughputTimer from ..engine import DeepSpeedEngine, MEMORY_OPT_ALLREDUCE_SIZE from ..utils import PartitionedTensor from ..dataloader import RepeatingLoader from .module import PipelineModule, PipelineError from . import p2p from . import schedule def is_even(number): return number % 2 == 0
null
10,328
from types import MethodType import torch from deepspeed import comm as dist from deepspeed.utils import logger from deepspeed.utils.timer import ThroughputTimer from ..engine import DeepSpeedEngine, MEMORY_OPT_ALLREDUCE_SIZE from ..utils import PartitionedTensor from ..dataloader import RepeatingLoader from .module import PipelineModule, PipelineError from . import p2p from . import schedule def _tensor_bytes(tensor): return tensor.numel() * tensor.element_size()
null
10,329
import os import torch import torch_nebula from deepspeed.runtime.checkpoint_engine.checkpoint_engine import \ CheckpointEngine from deepspeed.utils import logger, log_dist from deepspeed.nebula.constants import * def _get_tag_from_path(path): return os.path.basename(os.path.dirname(path))
null
10,330
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers def detach_variable(inputs, device=None): if isinstance(inputs, tuple): out = [] for inp in inputs: if not isinstance(inp, torch.Tensor): out.append(inp) continue requires_grad = inp.requires_grad if device is not None: x = inp.to(device=device) else: x = inp x = x.detach() x.requires_grad = requires_grad out.append(x) return tuple(out) else: raise RuntimeError( "Only tuple of tensors is supported. Got Unsupported input type: ", type(inputs).__name__)
null
10,331
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers The provided code snippet includes necessary dependencies for implementing the `_set_cuda_rng_state` function. Write a Python function `def _set_cuda_rng_state(new_state, device=-1)` to solve the following problem: Sets the random number generator state of the current GPU. Arguments: new_state (torch.ByteTensor): The desired state This function is adapted from PyTorch repo (torch.cuda.set_rng_state) with a single change: the input state is not cloned. Cloning caused major performance issues for +4 GPU cases. Here is the function: def _set_cuda_rng_state(new_state, device=-1): """Sets the random number generator state of the current GPU. Arguments: new_state (torch.ByteTensor): The desired state This function is adapted from PyTorch repo (torch.cuda.set_rng_state) with a single change: the input state is not cloned. Cloning caused major performance issues for +4 GPU cases. """ if hasattr(_C, '_cuda_setRNGState') and callable(_C._cuda_setRNGState): # older PyTorch def cb(): with device_ctx_manager(device): _C._cuda_setRNGState(new_state) else: # newer PyTorch if device == -1: device = torch.device('cuda') elif isinstance(device, str): device = torch.device(device) elif isinstance(device, int): device = torch.device('cuda', device) def cb(): idx = device.index if idx is None: idx = torch.cuda.current_device() default_generator = torch.cuda.default_generators[idx] default_generator.set_state(new_state) _lazy_call(cb)
Sets the random number generator state of the current GPU. Arguments: new_state (torch.ByteTensor): The desired state This function is adapted from PyTorch repo (torch.cuda.set_rng_state) with a single change: the input state is not cloned. Cloning caused major performance issues for +4 GPU cases.
10,332
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers _CUDA_RNG_STATE_TRACKER = CudaRNGStatesTracker() The provided code snippet includes necessary dependencies for implementing the `get_cuda_rng_tracker` function. Write a Python function `def get_cuda_rng_tracker()` to solve the following problem: Get cuda rng tracker. Here is the function: def get_cuda_rng_tracker(): """Get cuda rng tracker.""" return _CUDA_RNG_STATE_TRACKER
Get cuda rng tracker.
10,333
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers mpu = None _MODEL_PARALLEL_RNG_TRACKER_NAME = 'model-parallel-rng' _CUDA_RNG_STATE_TRACKER = CudaRNGStatesTracker() def reset(): """Resets memory buffers related to contiguous memory optimizations. Should be called during eval when multiple forward propagations are computed without any backward propagation that usually clears these buffers. Arguments: None Return: None """ if CONTIGUOUS_CHECKPOINTING: global data_offsets, size_offsets global contiguous_data_buffers, contiguous_size_buffers for buffers in contiguous_data_buffers: buffers = [] # frees up all the pointers to the checkpoints except for the ones # stored by save for backward contiguous_data_buffers = [] contiguous_size_buffers = [] data_offsets = [] size_offsets = [] def bwc_tensor_model_parallel_rank(mpu=None): """Backwards-compatible way of querying the tensor model parallel rank from an ``mpu`` object. *Tensor* model parallelism means that tensors are physically split across processes. This contrasts with *pipeline* model parallelism, in which the layers are partitioned but tensors left intact. The API for tensor model parallelism has changed across versions and this helper provides a best-effort implementation across versions of ``mpu`` objects. The preferred mechanism is ``mpu.get_tensor_model_parallel_rank()``. This should "just work" with both Megatron-LM and DeepSpeed's pipeline parallelism. Args: mpu (model parallel unit, optional): The tensor model parallel rank. If ``mpu=None``, returns 0. Defaults to ``None``. Returns: int: the rank """ if mpu is None: # No model parallelism in easy :) return 0 if hasattr(mpu, 'get_tensor_model_parallel_rank'): # New Megatron and DeepSpeed convention (post pipeline-parallelism release) return mpu.get_tensor_model_parallel_rank() elif hasattr(mpu, 'get_slice_parallel_rank'): # Some DeepSpeed + pipeline parallelism versions return mpu.get_slice_parallel_rank() else: # Deprecated Megatron and DeepSpeed convention return mpu.get_model_parallel_rank() The provided code snippet includes necessary dependencies for implementing the `model_parallel_cuda_manual_seed` function. Write a Python function `def model_parallel_cuda_manual_seed(seed)` to solve the following problem: Initialize model parallel cuda seed. This function should be called after the model parallel is initialized. Also, no torch.cuda.manual_seed should be called after this function. Basically, this is replacement for that function. Two set of RNG states are tracked: default state: This is for data parallelism and is the same among a set of model parallel GPUs but different across different model parallel groups. This is used for example for dropout in the non-model-parallel regions. model-parallel state: This state is different among a set of model parallel GPUs, but the same across data parallel groups. This is used for example for dropout in model parallel regions. Here is the function: def model_parallel_cuda_manual_seed(seed): """Initialize model parallel cuda seed. This function should be called after the model parallel is initialized. Also, no torch.cuda.manual_seed should be called after this function. Basically, this is replacement for that function. Two set of RNG states are tracked: default state: This is for data parallelism and is the same among a set of model parallel GPUs but different across different model parallel groups. This is used for example for dropout in the non-model-parallel regions. model-parallel state: This state is different among a set of model parallel GPUs, but the same across data parallel groups. This is used for example for dropout in model parallel regions. """ global mpu tp_rank = bwc_tensor_model_parallel_rank(mpu) # 2718 is just for fun and any POSITIVE value will work. offset = seed + 2718 model_parallel_seed = offset + tp_rank # Data parallel gets the original seed. data_parallel_seed = seed if dist.get_rank() == 0: logger.info( '> initializing model parallel cuda seeds on global rank {}, ' 'model parallel rank {}, and data parallel rank {} with ' 'model parallel seed: {} and data parallel seed: {}'.format( dist.get_rank(), tp_rank, mpu.get_data_parallel_rank(), model_parallel_seed, data_parallel_seed), ) _CUDA_RNG_STATE_TRACKER.reset() # Set the default state. torch.cuda.manual_seed(data_parallel_seed) # and model parallel state. _CUDA_RNG_STATE_TRACKER.add(_MODEL_PARALLEL_RNG_TRACKER_NAME, model_parallel_seed)
Initialize model parallel cuda seed. This function should be called after the model parallel is initialized. Also, no torch.cuda.manual_seed should be called after this function. Basically, this is replacement for that function. Two set of RNG states are tracked: default state: This is for data parallelism and is the same among a set of model parallel GPUs but different across different model parallel groups. This is used for example for dropout in the non-model-parallel regions. model-parallel state: This state is different among a set of model parallel GPUs, but the same across data parallel groups. This is used for example for dropout in model parallel regions.
10,334
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers mp_rank = None mp_size = None mp_group = None def is_activation_to_checkpoint(item): """ Is an activation to be checkpointed """ global mp_size return torch.is_tensor(item) and item.is_floating_point() and item.numel() >= mp_size def gather_partitioned_activations(tensors, device=None): global mp_rank, mp_size, mp_group assert len(tensors) % 2 == 0, f'Expected even count of tensors, instead got {len(tensors)}' inputs = [] num_args = int(len(tensors) / 2) for i in range(num_args): item = tensors[2 * i] size = tensors[2 * i + 1] if not is_activation_to_checkpoint(item): inputs.append(item) continue # don't need to do all_gather if model parallel size is 1 if mp_size == 1: item = item.view(list(size.numpy())) inputs.append(item) continue partition_size = item.numel() tensor_size = partition_size * mp_size if device is not None: flat_tensor = torch.zeros([tensor_size], dtype=item.dtype, device=device) else: flat_tensor = torch.zeros([tensor_size], dtype=item.dtype, device=item.device) partitions = [] for i in range(mp_size): part_i = flat_tensor.narrow(0, partition_size * i, partition_size) if i == mp_rank: part_i.copy_(item) partitions.append(part_i) if mp_group is not None: dist.all_gather(partitions, partitions[mp_rank], group=mp_group) input_tensor = flat_tensor.view(list(size.numpy())) item.data = input_tensor.data inputs.append(item) return tuple(inputs)
null
10,335
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers The provided code snippet includes necessary dependencies for implementing the `extract_tensors` function. Write a Python function `def extract_tensors(all_objects)` to solve the following problem: Separate objects in list/tuple into tensors and non-tensors and create a mapping to enable re-aggregation. The order of tensors and non-tensors is preserved in their respective output groups. Parameters: all_objects (list/tuple): Objects containing tensors and non-tensors to be split. Returns: tuple: Containing tensors, non-tensors, and bools of whether each position in original list/tuple was a tensor. Here is the function: def extract_tensors(all_objects): """ Separate objects in list/tuple into tensors and non-tensors and create a mapping to enable re-aggregation. The order of tensors and non-tensors is preserved in their respective output groups. Parameters: all_objects (list/tuple): Objects containing tensors and non-tensors to be split. Returns: tuple: Containing tensors, non-tensors, and bools of whether each position in original list/tuple was a tensor. """ tensor_objects = [v for v in all_objects if torch.is_tensor(v)] non_tensor_objects = [v for v in all_objects if not torch.is_tensor(v)] tensor_flags = [torch.is_tensor(v) for v in all_objects] if type(all_objects) is tuple: return tuple(tensor_objects), tuple(non_tensor_objects), tuple(tensor_flags) return tensor_objects, non_tensor_objects, tensor_flags
Separate objects in list/tuple into tensors and non-tensors and create a mapping to enable re-aggregation. The order of tensors and non-tensors is preserved in their respective output groups. Parameters: all_objects (list/tuple): Objects containing tensors and non-tensors to be split. Returns: tuple: Containing tensors, non-tensors, and bools of whether each position in original list/tuple was a tensor.
10,336
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers PARTITION_ACTIVATIONS = False The provided code snippet includes necessary dependencies for implementing the `merge_tensors` function. Write a Python function `def merge_tensors(tensor_objects, non_tensor_objects, tensor_flags)` to solve the following problem: Merge two lists (or tuples) of tensors and non-tensors using a mapping of positions in merged list (or tuple). Parameters: tensor_objects (list/tuple): Tensors to merge. non_tensor_objects (list/tuple): Non-tensors to merge. tensor_flags (list/tuple): Indicates whether each position in output is a tensor. Returns: tuple: Merge of tensors and non-tensors Here is the function: def merge_tensors(tensor_objects, non_tensor_objects, tensor_flags): """ Merge two lists (or tuples) of tensors and non-tensors using a mapping of positions in merged list (or tuple). Parameters: tensor_objects (list/tuple): Tensors to merge. non_tensor_objects (list/tuple): Non-tensors to merge. tensor_flags (list/tuple): Indicates whether each position in output is a tensor. Returns: tuple: Merge of tensors and non-tensors """ merged_objects = [] tensor_idx = 0 non_tensor_idx = 0 real_tensor_flags = None # remove the flags that are assigned to the size of the flattened tensors if PARTITION_ACTIVATIONS: real_tensor_flags = [] previous_flag = False for flag in tensor_flags: if previous_flag: previous_flag = False continue previous_flag = flag real_tensor_flags.append(flag) else: real_tensor_flags = tensor_flags for is_tensor in real_tensor_flags: if is_tensor: merged_objects.append(tensor_objects[tensor_idx]) tensor_idx += 1 else: merged_objects.append(non_tensor_objects[non_tensor_idx]) non_tensor_idx += 1 return tuple(merged_objects)
Merge two lists (or tuples) of tensors and non-tensors using a mapping of positions in merged list (or tuple). Parameters: tensor_objects (list/tuple): Tensors to merge. non_tensor_objects (list/tuple): Non-tensors to merge. tensor_flags (list/tuple): Indicates whether each position in output is a tensor. Returns: tuple: Merge of tensors and non-tensors
10,337
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers num_layers = None contiguous_size_buffers = [] size_offsets = [] def is_activation_to_checkpoint(item): def get_partitioned_activations_for_backward(args, inputs, contiguous_checkpoint): global contiguous_size_buffers, size_offsets new_args = [] num_non_fp_tensors = 0 for arg_index, (arg, inp) in enumerate(zip(args, inputs)): size = torch.tensor(arg.size()) if torch.is_tensor(arg) else None if not is_activation_to_checkpoint(arg): new_args.append(arg) new_args.append(size) num_non_fp_tensors += 1 continue arg.data = inp.data new_args.append(arg) i = arg_index - num_non_fp_tensors if contiguous_checkpoint: numel = size.numel() if i >= len(contiguous_size_buffers): tmp = torch.tensor(()) contiguous_size_buffers.append( tmp.new_empty([numel * num_layers], dtype=size.dtype, device=size.device)) size_offsets.append(0) elif contiguous_size_buffers[i] is None: tmp = torch.tensor(()) contiguous_size_buffers[i] = tmp.new_empty([numel * num_layers], dtype=size.dtype, device=size.device) size_offsets[i] = 0 contiguous_size = contiguous_size_buffers[i].narrow( 0, size_offsets[i], numel).data.copy_(size.data) contiguous_size = contiguous_size.view_as(size) size_offsets[i] = size_offsets[i] + numel new_args.append(contiguous_size) else: new_args.append(size) return new_args
null
10,338
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers def is_activation_to_checkpoint(item): """ Is an activation to be checkpointed """ global mp_size return torch.is_tensor(item) and item.is_floating_point() and item.numel() >= mp_size def get_cpu_activations_for_backward(args, inputs): new_args = [] for i, (arg, inp) in enumerate(zip(args, inputs)): if not is_activation_to_checkpoint(arg): new_args.append(arg) continue arg.data = inp.data new_args.append(arg) return new_args
null
10,339
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers class CheckpointFunction(torch.autograd.Function): """This function is adapted from torch.utils.checkpoint with two main changes: 1) torch.cuda.set_rng_state is replaced with `_set_cuda_rng_state` 2) the states in the model parallel tracker are also properly tracked/set/reset. 3) Performance activation partitioning, contiguous memory optimization 4) CPU Checkpointing 5) Profile forward and backward functions """ def forward(ctx, run_function, all_outputs, *args): global mpu, timers, SYNCHRONIZE, PROFILE_TIME def save_args_for_backward(*all_args): tensor_args, non_tensor_args, tensor_flags = extract_tensors(all_objects=all_args) ctx.deepspeed_saved_tensors = tensor_args ctx.non_tensor_args = non_tensor_args ctx.tensor_flags = tensor_flags if SYNCHRONIZE: torch.cuda.synchronize() if timers is None and PROFILE_TIME: timers = Timers() if PROFILE_TIME: timers('forward').start() ctx.run_function = run_function global num_layers global mp_rank, mp_size, mp_group global contiguous_data_buffers, contiguous_size_buffers global data_offsets, size_offsets if mp_rank is None: if mpu is not None: if hasattr(mpu, 'get_tensor_model_parallel_rank'): mp_rank = mpu.get_tensor_model_parallel_rank() mp_size = mpu.get_tensor_model_parallel_world_size() mp_group = mpu.get_tensor_model_parallel_group() else: mp_rank = mpu.get_model_parallel_rank() mp_size = mpu.get_model_parallel_world_size() mp_group = mpu.get_model_parallel_group() else: mp_rank = 0 mp_size = 1 mp_group = None global cuda_device, transport_stream, PARTITION_ACTIVATIONS, buffer_0, buffer_1, buffer_0_offset, buffer_1_offset if cuda_device is None: see_memory_usage("First Forward Beginning", force=False) if dist.get_rank() == 0: logger.info(f"Activation Checkpointing Information") logger.info( f"----Partition Activations {PARTITION_ACTIVATIONS}, CPU CHECKPOINTING {CPU_CHECKPOINT}" ) logger.info( f"----contiguous Memory Checkpointing {CONTIGUOUS_CHECKPOINTING} with {num_layers} total layers" ) logger.info(f"----Synchronization {SYNCHRONIZE}") logger.info(f"----Profiling time in checkpointing {PROFILE_TIME}") cuda_device = torch.cuda.current_device() transport_stream = torch.cuda.Stream(device=cuda_device) if PARTITION_ACTIVATIONS: inputs = partition_activations(args, CPU_CHECKPOINT, CONTIGUOUS_CHECKPOINTING) elif CPU_CHECKPOINT: inputs = copy_to_device(args, device=torch.device('cpu'), criterion_func=is_activation_to_checkpoint) # just in case something funky is happening such as reuse of inputs inputs_cuda = copy_to_device(args, device=cuda_device, criterion_func=is_activation_to_checkpoint) # Copy the rng states. ctx.fwd_cpu_rng_state = torch.get_rng_state() ctx.fwd_cuda_rng_state = torch.cuda.get_rng_state() ctx.fwd_cuda_rng_state_tracker = get_cuda_rng_tracker().get_states() see_memory_usage("Before running forward on the layer", force=False) # ctx.save_for_backward(*args) with torch.no_grad(): outputs = run_function(*inputs_cuda) see_memory_usage("After running forward on the layer", force=False) del inputs_cuda if PARTITION_ACTIVATIONS: new_args = get_partitioned_activations_for_backward( args, inputs, CONTIGUOUS_CHECKPOINTING) assert len(new_args) % 2 == 0, f'save_for_backward called with odd number of args, {len(new_args)}' save_args_for_backward(*new_args) elif CPU_CHECKPOINT: new_args = get_cpu_activations_for_backward(args, inputs) save_args_for_backward(*new_args) else: save_args_for_backward(*args) if PROFILE_TIME: timers('forward').stop() timers.log(['forward']) if SYNCHRONIZE: torch.cuda.synchronize() # Tensors returned from forward() may not be differentiable. if torch.is_tensor(outputs): non_grad_outputs = [outputs] if not outputs.is_floating_point() else [] else: non_grad_outputs = [ o for o in outputs if torch.is_tensor(o) and not o.is_floating_point() ] ctx.mark_non_differentiable(*non_grad_outputs) if torch.is_tensor(outputs): all_outputs += [outputs] return outputs else: all_outputs += outputs outputs, _, _ = extract_tensors(all_objects=outputs) return tuple(outputs) def backward(ctx, *grads): global timers see_memory_usage("In backward", force=False) # removing pointers to the contiguous buffer memory # so that they can be garbage collected once the checkpoints # have been used if SYNCHRONIZE: torch.cuda.synchronize() if PROFILE_TIME: timers('backward').start() if CONTIGUOUS_CHECKPOINTING: global data_offsets, size_offsets global contiguous_data_buffers, contiguous_size_buffers for buffers in contiguous_data_buffers: buffers = [] # frees up all the pointers to the checkpoints except for the ones # stored by save for backward contiguous_data_buffers = [] contiguous_size_buffers = [] data_offsets = [] size_offsets = [] see_memory_usage("In backward checkpointing code", force=False) if not torch.autograd._is_checkpoint_valid(): raise RuntimeError("Checkpointing is not compatible with .grad(), " "please use .backward() if possible") global cuda_device, transport_stream, PARTITION_ACTIVATIONS if PARTITION_ACTIVATIONS: # with torch.cuda.stream(transport_stream): inputs = gather_partitioned_activations( ctx.deepspeed_saved_tensors, device=cuda_device if CPU_CHECKPOINT else None) detached_inputs = detach_variable(inputs) elif CPU_CHECKPOINT: inputs = move_to_device(ctx.deepspeed_saved_tensors, cuda_device, is_activation_to_checkpoint) detached_inputs = detach_variable(inputs) else: inputs = ctx.deepspeed_saved_tensors detached_inputs = detach_variable(inputs) # Add non tensor input args detached_inputs = merge_tensors(tensor_objects=detached_inputs, non_tensor_objects=ctx.non_tensor_args, tensor_flags=ctx.tensor_flags) # Store the current states. bwd_cpu_rng_state = torch.get_rng_state() bwd_cuda_rng_state = torch.cuda.get_rng_state() bwd_cuda_rng_state_tracker = get_cuda_rng_tracker().get_states() # Set the states to what it used to be before the forward pass. torch.set_rng_state(ctx.fwd_cpu_rng_state) _set_cuda_rng_state(ctx.fwd_cuda_rng_state) get_cuda_rng_tracker().set_states(ctx.fwd_cuda_rng_state_tracker) # if PARTITION_ACTIVATIONS: # current_stream=torch.cuda.current_stream() # current_stream.wait_stream(transport_stream) see_memory_usage("In backward checkpointing code before forward", force=False) with torch.enable_grad(): outputs = ctx.run_function(*detached_inputs) see_memory_usage("In backward checkpointing code after forward", force=False) # Set the states back to what it was at the start of this function. torch.set_rng_state(bwd_cpu_rng_state) _set_cuda_rng_state(bwd_cuda_rng_state) get_cuda_rng_tracker().set_states(bwd_cuda_rng_state_tracker) if isinstance(outputs, torch.Tensor): outputs = (outputs, ) # Filter out non tensor outputs outputs, _, _ = extract_tensors(all_objects=outputs) # Construct arguments to autograd.backward(). # This is usually just outputs and grads, but forward() can return tensors that # are not differentiable. output_tensors = [] grad_tensors = [] for out, grad in zip(outputs, grads): if out.requires_grad: output_tensors.append(out) grad_tensors.append(grad) see_memory_usage("In backward checkpointing code before backward", force=False) torch.autograd.backward(output_tensors, grad_tensors) # Force clear our stashed tensors to prevent a memory leak in certain scenarios ctx.deepspeed_saved_tensors = None ctx.non_tensor_args = None ctx.tensor_flags = None see_memory_usage("After backward checkpointing code after backward", force=False) if PROFILE_TIME: timers('backward').stop() timers.log(['backward']) if SYNCHRONIZE: torch.cuda.synchronize() ret_list = [None, None] # first None for ctx for inp in detached_inputs: if torch.is_tensor(inp): ret_list.append(inp.grad) else: ret_list.append(None) return tuple(ret_list) The provided code snippet includes necessary dependencies for implementing the `checkpoint` function. Write a Python function `def checkpoint(function, *args)` to solve the following problem: Checkpoint a model or part of the model. This has been directly copied from torch.utils.checkpoint. Here is the function: def checkpoint(function, *args): """Checkpoint a model or part of the model. This has been directly copied from torch.utils.checkpoint. """ all_outputs = [] CheckpointFunction.apply(function, all_outputs, *args) if len(all_outputs) == 1: return all_outputs[0] else: return tuple(all_outputs)
Checkpoint a model or part of the model. This has been directly copied from torch.utils.checkpoint.
10,340
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers PARTITION_ACTIVATIONS = False def partition_activations_in_checkpoint(partition_activation): global PARTITION_ACTIVATIONS PARTITION_ACTIVATIONS = partition_activation if dist.get_rank() == 0: logger.info( f"**************Partition Activations {PARTITION_ACTIVATIONS}************")
null
10,341
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers num_layers = None def set_num_layers(nlayers): global num_layers num_layers = nlayers
null
10,342
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers deepspeed_checkpointing_enabled = False mpu = None num_layers = None PARTITION_ACTIVATIONS = False CPU_CHECKPOINT = False CONTIGUOUS_CHECKPOINTING = False SYNCHRONIZE = False PROFILE_TIME = False def _configure_using_config_file(config, mpu=None): global num_layers, PARTITION_ACTIVATIONS, CONTIGUOUS_CHECKPOINTING, \ CPU_CHECKPOINT, SYNCHRONIZE, PROFILE_TIME config = DeepSpeedConfig(config, mpu=mpu).activation_checkpointing_config if dist.get_rank() == 0: logger.info(config.repr()) PARTITION_ACTIVATIONS = config.partition_activations CONTIGUOUS_CHECKPOINTING = config.contiguous_memory_optimization num_layers = config.number_checkpoints CPU_CHECKPOINT = config.cpu_checkpointing SYNCHRONIZE = config.synchronize_checkpoint_boundary PROFILE_TIME = config.profile def _configure_defaults(): global mpu, num_layers, deepspeed_checkpointing_enabled global PARTITION_ACTIVATIONS, CONTIGUOUS_CHECKPOINTING, \ CPU_CHECKPOINT, SYNCHRONIZE, PROFILE_TIME PARTITION_ACTIVATIONS = False CONTIGUOUS_CHECKPOINTING = False num_layers = False CPU_CHECKPOINT = False SYNCHRONIZE = False PROFILE_TIME = False deepspeed_checkpointing_enabled = True The provided code snippet includes necessary dependencies for implementing the `configure` function. Write a Python function `def configure( mpu_, deepspeed_config=None, partition_activations=None, contiguous_checkpointing=None, num_checkpoints=None, checkpoint_in_cpu=None, synchronize=None, profile=None, )` to solve the following problem: Configure DeepSpeed Activation Checkpointing. Arguments: mpu_: Optional: An object that implements the following methods get_model_parallel_rank/group/world_size, and get_data_parallel_rank/group/world_size deepspeed_config: Optional: DeepSpeed Config json file when provided will be used to configure DeepSpeed Activation Checkpointing partition_activations: Optional: Partitions activation checkpoint across model parallel GPUs when enabled. By default False. Will overwrite deepspeed_config if provided contiguous_checkpointing: Optional: Copies activation checkpoints to a contiguous memory buffer. Works only with homogeneous checkpoints when partition_activations is enabled. Must provide num_checkpoints. By default False. Will overwrite deepspeed_config if provided num_checkpoints: Optional: Number of activation checkpoints stored during the forward propagation of the model. Used to calculate the buffer size for contiguous_checkpointing Will overwrite deepspeed_config if provided checkpoint_in_cpu: Optional: Moves the activation checkpoint to CPU. Only works with partition_activation. Default is false. Will overwrite deepspeed_config if provided synchronize: Optional: Performs torch.cuda.synchronize() at the beginning and end of each call to deepspeed.checkpointing.checkpoint for both forward and backward pass. By default false. Will overwrite deepspeed_config if provided profile: Optional: Logs the forward and backward time for each deepspeed.checkpointing.checkpoint invocation. Will overwrite deepspeed_config if provided Returns: None Here is the function: def configure( mpu_, deepspeed_config=None, partition_activations=None, contiguous_checkpointing=None, num_checkpoints=None, checkpoint_in_cpu=None, synchronize=None, profile=None, ): """Configure DeepSpeed Activation Checkpointing. Arguments: mpu_: Optional: An object that implements the following methods get_model_parallel_rank/group/world_size, and get_data_parallel_rank/group/world_size deepspeed_config: Optional: DeepSpeed Config json file when provided will be used to configure DeepSpeed Activation Checkpointing partition_activations: Optional: Partitions activation checkpoint across model parallel GPUs when enabled. By default False. Will overwrite deepspeed_config if provided contiguous_checkpointing: Optional: Copies activation checkpoints to a contiguous memory buffer. Works only with homogeneous checkpoints when partition_activations is enabled. Must provide num_checkpoints. By default False. Will overwrite deepspeed_config if provided num_checkpoints: Optional: Number of activation checkpoints stored during the forward propagation of the model. Used to calculate the buffer size for contiguous_checkpointing Will overwrite deepspeed_config if provided checkpoint_in_cpu: Optional: Moves the activation checkpoint to CPU. Only works with partition_activation. Default is false. Will overwrite deepspeed_config if provided synchronize: Optional: Performs torch.cuda.synchronize() at the beginning and end of each call to deepspeed.checkpointing.checkpoint for both forward and backward pass. By default false. Will overwrite deepspeed_config if provided profile: Optional: Logs the forward and backward time for each deepspeed.checkpointing.checkpoint invocation. Will overwrite deepspeed_config if provided Returns: None """ global mpu, num_layers, deepspeed_checkpointing_enabled global PARTITION_ACTIVATIONS, CONTIGUOUS_CHECKPOINTING, \ CPU_CHECKPOINT, SYNCHRONIZE, PROFILE_TIME _configure_defaults() if mpu_ is not None: mpu = mpu_ if deepspeed_config is not None: _configure_using_config_file(deepspeed_config, mpu=mpu) if partition_activations is not None: PARTITION_ACTIVATIONS = partition_activations if contiguous_checkpointing is not None: CONTIGUOUS_CHECKPOINTING = contiguous_checkpointing if num_checkpoints is not None: num_layers = num_checkpoints if checkpoint_in_cpu is not None: CPU_CHECKPOINT = checkpoint_in_cpu if synchronize is not None: SYNCHRONIZE = synchronize if profile is not None: PROFILE_TIME = profile if CONTIGUOUS_CHECKPOINTING: assert PARTITION_ACTIVATIONS, "Contiguous Checkpointing is only available with partitioned activations. Set partitioned activations to true in deepspeed config" if CONTIGUOUS_CHECKPOINTING: assert num_layers is not None, "Must specify the number of layers with contiguous memory checkpointing"
Configure DeepSpeed Activation Checkpointing. Arguments: mpu_: Optional: An object that implements the following methods get_model_parallel_rank/group/world_size, and get_data_parallel_rank/group/world_size deepspeed_config: Optional: DeepSpeed Config json file when provided will be used to configure DeepSpeed Activation Checkpointing partition_activations: Optional: Partitions activation checkpoint across model parallel GPUs when enabled. By default False. Will overwrite deepspeed_config if provided contiguous_checkpointing: Optional: Copies activation checkpoints to a contiguous memory buffer. Works only with homogeneous checkpoints when partition_activations is enabled. Must provide num_checkpoints. By default False. Will overwrite deepspeed_config if provided num_checkpoints: Optional: Number of activation checkpoints stored during the forward propagation of the model. Used to calculate the buffer size for contiguous_checkpointing Will overwrite deepspeed_config if provided checkpoint_in_cpu: Optional: Moves the activation checkpoint to CPU. Only works with partition_activation. Default is false. Will overwrite deepspeed_config if provided synchronize: Optional: Performs torch.cuda.synchronize() at the beginning and end of each call to deepspeed.checkpointing.checkpoint for both forward and backward pass. By default false. Will overwrite deepspeed_config if provided profile: Optional: Logs the forward and backward time for each deepspeed.checkpointing.checkpoint invocation. Will overwrite deepspeed_config if provided Returns: None
10,343
import copy import torch import contextlib from deepspeed import comm as dist import mmap from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.utils import logger from deepspeed.runtime.utils import copy_to_device, move_to_device, see_memory_usage, bwc_tensor_model_parallel_rank from deepspeed.utils.timer import SynchronizedWallClockTimer as Timers deepspeed_checkpointing_enabled = False The provided code snippet includes necessary dependencies for implementing the `is_configured` function. Write a Python function `def is_configured()` to solve the following problem: True if deepspeed activation checkpointing has been configured by calling deepspeed.checkpointing.configure, else returns false Arguments: None Return: True of configured, else False Here is the function: def is_configured(): """True if deepspeed activation checkpointing has been configured by calling deepspeed.checkpointing.configure, else returns false Arguments: None Return: True of configured, else False """ return deepspeed_checkpointing_enabled
True if deepspeed activation checkpointing has been configured by calling deepspeed.checkpointing.configure, else returns false Arguments: None Return: True of configured, else False
10,344
import os import re import stat import torch import hashlib from collections import defaultdict, OrderedDict from shutil import copyfile from torch.nn.modules import Module from torch.nn.parameter import Parameter from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler from typing import Callable, Dict, Union, Iterable import deepspeed from deepspeed.runtime.utils import see_memory_usage, DummyOptim from .zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.stage_1_and_2 import DeepSpeedZeroOptimizer from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus from deepspeed.runtime.zero.utils import is_zero_supported_optimizer, ZeRORuntimeException from deepspeed.runtime.zero.parameter_offload import DeepSpeedZeRoOffload from deepspeed.runtime.zero.config import ZERO_OPTIMIZATION from deepspeed.runtime.fp16.fused_optimizer import FP16_Optimizer from deepspeed.runtime.fp16.unfused_optimizer import FP16_UnfusedOptimizer from deepspeed.runtime.bf16_optimizer import BF16_Optimizer from deepspeed.runtime.config import DeepSpeedConfig, DEEPSPEED_OPTIMIZERS, \ ADAGRAD_OPTIMIZER, ADAM_OPTIMIZER, ADAMW_OPTIMIZER, LAMB_OPTIMIZER, ONEBIT_ADAM_OPTIMIZER, ONEBIT_LAMB_OPTIMIZER, \ TORCH_ADAM_PARAM, ADAM_W_MODE, ADAM_W_MODE_DEFAULT, ZERO_ONE_ADAM_OPTIMIZER from deepspeed.runtime.dataloader import DeepSpeedDataLoader from deepspeed.runtime.constants import \ ROUTE_TRAIN, ROUTE_PREDICT, ROUTE_EVAL, \ PLD_THETA, PLD_GAMMA, BFLOAT16, FP16, AMP from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.compression import compression_scheduler from deepspeed.compression.constants import \ WEIGHT_QUANTIZE_IN_FORWARD_ENABLED, \ WEIGHT_QUANTIZATION, SHARED_PARAMETERS, \ WEIGHT_QUANTIZE_ENABLED, \ WEIGHT_QUANTIZE_GROUPS, \ WEIGHT_QUANTIZE_FP16_MIXED_QUANTIZE, \ WEIGHT_QUANTIZE_CHANGE_RATIO, \ WEIGHT_QUANTIZE_TYPE, \ WEIGHT_QUANTIZE_ROUNDING, \ WEIGHT_QUANTIZE_VERBOSE, \ WEIGHT_QUANTIZE_KERNEL from deepspeed.checkpoint.constants import OPTIMIZER_STATE_DICT from deepspeed.runtime.sparse_tensor import SparseTensor from deepspeed.runtime import lr_schedules from deepspeed.utils import groups from deepspeed.utils import logger, log_dist, instrument_w_nvtx from deepspeed.utils.timer import ThroughputTimer, SynchronizedWallClockTimer from deepspeed.utils.debug import debug_extract_module_and_param_names from deepspeed.monitor.monitor import MonitorMaster from deepspeed.runtime.progressive_layer_drop import ProgressiveLayerDrop from deepspeed.runtime.utils import clip_grad_norm_ from deepspeed.runtime.eigenvalue import Eigenvalue from deepspeed.runtime.data_pipeline.curriculum_scheduler import CurriculumScheduler from deepspeed.runtime.checkpoint_engine.torch_checkpoint_engine import TorchCheckpointEngine from .pipe.module import PipelineModule from .utils import ensure_directory_exists, get_ma_status from ..ops.op_builder import UtilsBuilder from ..ops.adam import FusedAdam from ..moe.sharded_moe import TopKGate, MOELayer from ..moe.layer import MoE from ..moe.utils import is_moe_param from ..git_version_info import version from deepspeed.profiling.flops_profiler.profiler import FlopsProfiler from deepspeed.utils.logging import print_json_dist from deepspeed.inference.config import DtypeEnum class SparseTensor(object): def __init__(self, dense_tensor=None): def to_coo_tensor(self): def type(): def to_dense(self): def sparse_size(self): def add(self, b): def __str__(self): def __repr__(self): def split_half_float_double_sparse(tensors): supported_types = [ "torch.cuda.HalfTensor", "torch.cuda.FloatTensor", "torch.cuda.DoubleTensor", "torch.cuda.BFloat16Tensor", SparseTensor.type() ] for t in tensors: assert t.type() in supported_types, f"attempting to reduce an unsupported grad type: {t.type()}" buckets = [] for i, dtype in enumerate(supported_types): bucket = [t for t in tensors if t.type() == dtype] if bucket: buckets.append((dtype, bucket)) return buckets
null
10,345
import os import re import stat import torch import hashlib from collections import defaultdict, OrderedDict from shutil import copyfile from torch.nn.modules import Module from torch.nn.parameter import Parameter from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler from typing import Callable, Dict, Union, Iterable import deepspeed from deepspeed.runtime.utils import see_memory_usage, DummyOptim from .zero.offload_config import OffloadDeviceEnum from deepspeed.runtime.zero.stage_1_and_2 import DeepSpeedZeroOptimizer from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus from deepspeed.runtime.zero.utils import is_zero_supported_optimizer, ZeRORuntimeException from deepspeed.runtime.zero.parameter_offload import DeepSpeedZeRoOffload from deepspeed.runtime.zero.config import ZERO_OPTIMIZATION from deepspeed.runtime.fp16.fused_optimizer import FP16_Optimizer from deepspeed.runtime.fp16.unfused_optimizer import FP16_UnfusedOptimizer from deepspeed.runtime.bf16_optimizer import BF16_Optimizer from deepspeed.runtime.config import DeepSpeedConfig, DEEPSPEED_OPTIMIZERS, \ ADAGRAD_OPTIMIZER, ADAM_OPTIMIZER, ADAMW_OPTIMIZER, LAMB_OPTIMIZER, ONEBIT_ADAM_OPTIMIZER, ONEBIT_LAMB_OPTIMIZER, \ TORCH_ADAM_PARAM, ADAM_W_MODE, ADAM_W_MODE_DEFAULT, ZERO_ONE_ADAM_OPTIMIZER from deepspeed.runtime.dataloader import DeepSpeedDataLoader from deepspeed.runtime.constants import \ ROUTE_TRAIN, ROUTE_PREDICT, ROUTE_EVAL, \ PLD_THETA, PLD_GAMMA, BFLOAT16, FP16, AMP from deepspeed.runtime.zero.config import ZeroStageEnum from deepspeed.compression import compression_scheduler from deepspeed.compression.constants import \ WEIGHT_QUANTIZE_IN_FORWARD_ENABLED, \ WEIGHT_QUANTIZATION, SHARED_PARAMETERS, \ WEIGHT_QUANTIZE_ENABLED, \ WEIGHT_QUANTIZE_GROUPS, \ WEIGHT_QUANTIZE_FP16_MIXED_QUANTIZE, \ WEIGHT_QUANTIZE_CHANGE_RATIO, \ WEIGHT_QUANTIZE_TYPE, \ WEIGHT_QUANTIZE_ROUNDING, \ WEIGHT_QUANTIZE_VERBOSE, \ WEIGHT_QUANTIZE_KERNEL from deepspeed.checkpoint.constants import OPTIMIZER_STATE_DICT from deepspeed.runtime.sparse_tensor import SparseTensor from deepspeed.runtime import lr_schedules from deepspeed.utils import groups from deepspeed.utils import logger, log_dist, instrument_w_nvtx from deepspeed.utils.timer import ThroughputTimer, SynchronizedWallClockTimer from deepspeed.utils.debug import debug_extract_module_and_param_names from deepspeed.monitor.monitor import MonitorMaster from deepspeed.runtime.progressive_layer_drop import ProgressiveLayerDrop from deepspeed.runtime.utils import clip_grad_norm_ from deepspeed.runtime.eigenvalue import Eigenvalue from deepspeed.runtime.data_pipeline.curriculum_scheduler import CurriculumScheduler from deepspeed.runtime.checkpoint_engine.torch_checkpoint_engine import TorchCheckpointEngine from .pipe.module import PipelineModule from .utils import ensure_directory_exists, get_ma_status from ..ops.op_builder import UtilsBuilder from ..ops.adam import FusedAdam from ..moe.sharded_moe import TopKGate, MOELayer from ..moe.layer import MoE from ..moe.utils import is_moe_param from ..git_version_info import version from deepspeed.profiling.flops_profiler.profiler import FlopsProfiler from deepspeed.utils.logging import print_json_dist from deepspeed.inference.config import DtypeEnum def print_configuration(args, name): logger.info("{}:".format(name)) for arg in sorted(vars(args)): dots = "." * (29 - len(arg)) logger.info(" {} {} {}".format(arg, dots, getattr(args, arg)))
null
10,346
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def search_error(filename): if not os.path.exists(filename): return "stderr.log does not exist" with open(filename) as f: for line in f: for s in ["Error", "error", "ERROR"]: idx = line.find(s) if idx != -1: return line[idx + len(s):].lstrip(": ") return None
null
10,347
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def was_interruptted(filename): if not os.path.exists(filename): return "stderr.log does not exist" with open(filename) as f: for line in f: s = "KeyboardInterrupt" idx = line.find(s) if idx != -1: return True return False
null
10,348
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def find_replace_str(value, replace_dict): if not isinstance(value, str): return str(value) matches = re.findall(r"\$[A-Za-z0-9_]+", value) for var in matches: var_key = var.replace("$", "").lower() if var_key == "nvme_path": continue assert var_key in replace_dict, f"unknown var key: {var_key}, in {replace_dict}" if isinstance(replace_dict[var_key], str): value = value.replace(var, replace_dict[var_key]) else: assert len(matches) == 1, "unable to replace multiple non-string matches" value = replace_dict[var_key] return value def find_replace(target, replace_dict): if isinstance(target, dict): for key, value in target.items(): if isinstance(value, str): target[key] = find_replace_str(value, replace_dict) if isinstance(value, list): for i in range(len(value)): value[i] = find_replace_str(value[i], replace_dict) if isinstance(value, dict): find_replace(value, replace_dict) elif isinstance(target, list): for i in range(len(target)): target[i] = str(find_replace_str(target[i], replace_dict))
null
10,349
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def get_list(val): if not isinstance(val, list): return [val] else: return val def combine_dict(d, u): for k, v in u.items(): if isinstance(v, collections.abc.Mapping): d[k] = combine_dict(d.get(k, {}), v) else: if k not in d: d[k] = v else: if not isinstance(d[k], list): d[k] = [d[k]] d[k].extend(i for i in get_list(v) if i not in d[k]) return d
null
10,350
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def get_val_by_key(d: dict, k): if k in d: return d[k] for v in d.values(): if isinstance(v, dict): return get_val_by_key(v, k) return None
null
10,351
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def set_val_by_key(d: dict, k, vv): if k in d: d[k] = vv for v in d.values(): if isinstance(v, dict): set_val_by_key(v, k, vv)
null
10,352
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def fetch_hostfile(hostfile_path): if not os.path.isfile(hostfile_path): logger.warning("Unable to find hostfile, will proceed with training " "with local resources only.") return None # e.g., worker-0 slots=16 with open(hostfile_path, 'r') as fd: resource_pool = collections.OrderedDict() for line in fd.readlines(): line = line.strip() if line == '': # skip empty lines continue try: hostname, slots = line.split() _, slot_count = slots.split("=") slot_count = int(slot_count) except ValueError as err: logger.error("Hostfile is not formatted correctly, unable to " "proceed with training.") raise err if hostname in resource_pool: logger.error("Hostfile contains duplicate hosts, unable to " "proceed with training.") raise ValueError("host {} is already defined".format(hostname)) resource_pool[hostname] = slot_count return resource_pool
null
10,353
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def validate_ds_config(config: dict): def is_False(config: dict, key): if config is None: return False return bool(config.get(key)) config_zero = config.get("zero_optimization", {}) if not config_zero: return True stage = config_zero.get("stage") offload = False if stage == 1: return True elif stage == 2: if is_False(config_zero, "cpu_offload") and is_False(config_zero, "cpu_offload_params"): return False elif stage == 3: offload_devices = ["cpu", "nvme"] if config_zero.get("offload_optimizer", {}).get("device") in offload_devices: offload = True if config_zero.get("offload_param", {}).get("device") in offload_devices: offload = True else: return True # HF requires that "ZeRO Offload can only work with DeepSpeed optimizers" if offload and not config.get("optimizer"): return False return True
null