id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
10,454 | import os
import sys
import json
import base64
import argparse
import subprocess
import collections
from copy import deepcopy
import signal
import time
import torch.cuda
from .multinode_runner import PDSHRunner, OpenMPIRunner, MVAPICHRunner, SlurmRunner
from .constants import PDSH_LAUNCHER, OPENMPI_LAUNCHER, MVAPICH_LA... | null |
10,455 | import os
import sys
import json
import base64
import argparse
import subprocess
import collections
from copy import deepcopy
import signal
import time
import torch.cuda
from .multinode_runner import PDSHRunner, OpenMPIRunner, MVAPICHRunner, SlurmRunner
from .constants import PDSH_LAUNCHER, OPENMPI_LAUNCHER, MVAPICH_LA... | null |
10,456 | import os
import sys
import json
import base64
import argparse
import subprocess
import collections
from copy import deepcopy
import signal
import time
import torch.cuda
from .multinode_runner import PDSHRunner, OpenMPIRunner, MVAPICHRunner, SlurmRunner
from .constants import PDSH_LAUNCHER, OPENMPI_LAUNCHER, MVAPICH_LA... | null |
10,457 | import os
import sys
import json
import base64
import argparse
import subprocess
import collections
from copy import deepcopy
import signal
import time
import torch.cuda
from .multinode_runner import PDSHRunner, OpenMPIRunner, MVAPICHRunner, SlurmRunner
from .constants import PDSH_LAUNCHER, OPENMPI_LAUNCHER, MVAPICH_LA... | null |
10,458 | import sys
import subprocess
import os
import json
import base64
import time
import signal
import psutil
from collections import defaultdict
from typing import Dict
from argparse import ArgumentParser, REMAINDER
from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT
from ..nebula.constants import DLTS_POD_ENV_PATH
from... | null |
10,459 | import sys
import subprocess
import os
import json
import base64
import time
import signal
import psutil
from collections import defaultdict
from typing import Dict
from argparse import ArgumentParser, REMAINDER
from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT
from ..nebula.constants import DLTS_POD_ENV_PATH
from... | null |
10,460 | import torch
import math
from torch import nn
from torch.nn import init
import deepspeed.comm as dist
from .utils import TopKBinarizer, SymQuantizer, AsymQuantizer, TernaryQuantizer, BinaryQuantizer
from deepspeed.utils import logger
g_mpu = None
The provided code snippet includes necessary dependencies for implementi... | All-reduce the the input tensor across model parallel group. |
10,461 | import torch
import math
from torch import nn
from torch.nn import init
import deepspeed.comm as dist
from .utils import TopKBinarizer, SymQuantizer, AsymQuantizer, TernaryQuantizer, BinaryQuantizer
from deepspeed.utils import logger
g_mpu = None
def split_tensor_along_last_dim(tensor, num_partitions, contiguous_split_... | Split the tensor along its last dimension and keep the corresponding slice. |
10,462 | import torch
import math
from torch import nn
from torch.nn import init
import deepspeed.comm as dist
from .utils import TopKBinarizer, SymQuantizer, AsymQuantizer, TernaryQuantizer, BinaryQuantizer
from deepspeed.utils import logger
g_mpu = None
The provided code snippet includes necessary dependencies for implementi... | Gather tensors and concatinate along the last dimension. |
10,463 | import torch
import math
from torch import nn
from torch.nn import init
import deepspeed.comm as dist
from .utils import TopKBinarizer, SymQuantizer, AsymQuantizer, TernaryQuantizer, BinaryQuantizer
from deepspeed.utils import logger
class _CopyToModelParallelRegion(torch.autograd.Function):
"""Pass the input to th... | null |
10,464 | import torch
import math
from torch import nn
from torch.nn import init
import deepspeed.comm as dist
from .utils import TopKBinarizer, SymQuantizer, AsymQuantizer, TernaryQuantizer, BinaryQuantizer
from deepspeed.utils import logger
class _ReduceFromModelParallelRegion(torch.autograd.Function):
def forward(ctx, i... | null |
10,465 | import torch
import math
from torch import nn
from torch.nn import init
import deepspeed.comm as dist
from .utils import TopKBinarizer, SymQuantizer, AsymQuantizer, TernaryQuantizer, BinaryQuantizer
from deepspeed.utils import logger
class _ScatterToModelParallelRegion(torch.autograd.Function):
"""Split the input a... | null |
10,466 | import torch
import math
from torch import nn
from torch.nn import init
import deepspeed.comm as dist
from .utils import TopKBinarizer, SymQuantizer, AsymQuantizer, TernaryQuantizer, BinaryQuantizer
from deepspeed.utils import logger
class _GatherFromModelParallelRegion(torch.autograd.Function):
"""Gather the input... | null |
10,467 | import re
from .helper import compression_preparation, fix_compression, recursive_getattr, is_module_compressible
from .config import get_compression_config
from ..runtime.config_utils import dict_raise_error_on_duplicate_keys
from .constants import *
import os
import json
def check_deepspeed_config(config):
if isi... | Compress a model: replace linear/conv2d layer with deepspeed compression-aware modules Args: model (`torch.nn.Module`) The model to compress. deepspeed_config (`DeepSpeedConfig`) The path of ds_config mpu The mpu module for Row/Column parallelism |
10,468 | import re
from .helper import compression_preparation, fix_compression, recursive_getattr, is_module_compressible
from .config import get_compression_config
from ..runtime.config_utils import dict_raise_error_on_duplicate_keys
from .constants import *
import os
import json
def check_deepspeed_config(config):
if isi... | Remove the redundancy of a model Args: model (`torch.nn.Module`) The model to compress. deepspeed_config (`DeepSpeedConfig`) The path of ds_config mpu The mpu module for Row/Column parallelism |
10,469 | import torch
from .basic_layer import Embedding_Compress, LinearLayer_Compress, Conv2dLayer_Compress, BNLayer_Compress, ColumnParallelLinear_Compress, RowParallelLinear_Compress
from .constants import *
def recursive_getattr(model, module_name):
"""
Recursively get the attribute of a module.
Args:
m... | This is a help function to convert conv1d to linear (e.g., convert GPT2 from HF) |
10,470 | from .abstract_accelerator import DeepSpeedAccelerator
ds_accelerator = None
def _validate_accelerator(accel_obj):
assert isinstance(accel_obj, DeepSpeedAccelerator), \
f'{accel_obj.__class__.__name__} accelerator is not subclass of DeepSpeedAccelerator'
# TODO: turn off is_available test since this bre... | null |
10,471 | from .abstract_accelerator import DeepSpeedAccelerator
ds_accelerator = None
def _validate_accelerator(accel_obj):
assert isinstance(accel_obj, DeepSpeedAccelerator), \
f'{accel_obj.__class__.__name__} accelerator is not subclass of DeepSpeedAccelerator'
# TODO: turn off is_available test since this bre... | null |
10,472 | import logging
import sys
import os
logger = LoggerFactory.create_logger(name="DeepSpeed", level=logging.INFO)
import logging
The provided code snippet includes necessary dependencies for implementing the `log_dist` function. Write a Python function `def log_dist(message, ranks=None, level=logging.INFO)` to solve the... | Log message when one of following condition meets + not dist.is_initialized() + dist.get_rank() in ranks if ranks is not None or ranks = [-1] Args: message (str) ranks (list) level (int) |
10,473 | import logging
import sys
import os
The provided code snippet includes necessary dependencies for implementing the `print_json_dist` function. Write a Python function `def print_json_dist(message, ranks=None, path=None)` to solve the following problem:
Print message when one of following condition meets + not dist.is_... | Print message when one of following condition meets + not dist.is_initialized() + dist.get_rank() in ranks if ranks is not None or ranks = [-1] Args: message (str) ranks (list) path (str) |
10,474 | import logging
import sys
import os
log_levels = {
"debug": logging.DEBUG,
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ERROR,
"critical": logging.CRITICAL,
}
def get_current_level():
"""
Return logger's current log level
"""
return logger.getEffectiveLevel()
T... | Args: max_log_level_str: maximum log level as a string Returns ``True`` if the current log_level is less or equal to the specified log level. Otherwise ``False``. Example: ``should_log_le("info")`` will return ``True`` if the current log level is either ``logging.INFO`` or ``logging.DEBUG`` |
10,475 | import argparse
import torch
import glob
import math
import os
import re
from collections import OrderedDict
from deepspeed.utils import logger
from deepspeed.checkpoint.constants import (DS_VERSION,
OPTIMIZER_STATE_DICT,
SINGLE_PAR... | Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed. Args: - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) -... |
10,476 | import argparse
import torch
import glob
import math
import os
import re
from collections import OrderedDict
from deepspeed.utils import logger
from deepspeed.checkpoint.constants import (DS_VERSION,
OPTIMIZER_STATE_DICT,
SINGLE_PAR... | 1. Put the provided model to cpu 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` 3. Load it into the provided model Args: - ``model``: the model object to update - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``t... |
10,477 | module_names = {}
param_names = {}
def debug_extract_module_and_param_names(model):
# extract the fully qualified names as soon as the model is acquired
global module_names
global param_names
# XXX: can probably make a map of param2module and vice-versa
module_names = {module: name for name, module... | null |
10,478 | def debug_module2name(module):
if module in module_names:
return module_names[module]
else:
return "unknown"
def debug_module2name_id(module):
return f"name={debug_module2name(module)} id={module.id}" | null |
10,479 | def debug_module2name(module):
def debug_module2name_class(module):
return f"name={debug_module2name(module)} {module.__class__.__name__}" | null |
10,480 | def debug_param2name(param):
if param in param_names:
return param_names[param]
else:
return "unknown"
def debug_param2name_id(param):
return f"name={debug_param2name(param)} id={param.ds_id}" | null |
10,481 | def debug_param2name(param):
if param in param_names:
return param_names[param]
else:
return "unknown"
def debug_param2name_id_shape(param):
return f"name={debug_param2name(param)} id={param.ds_id} shape={param.data.shape}" | null |
10,482 | def debug_param2name(param):
if param in param_names:
return param_names[param]
else:
return "unknown"
def debug_param2name_id_shape_device(param):
return f"name={debug_param2name(param)} id={param.ds_id} shape={param.data.shape} device={param.device}" | null |
10,483 | def debug_param2name(param):
if param in param_names:
return param_names[param]
else:
return "unknown"
def debug_param2name_id_numel(param):
return f"name={debug_param2name(param)} id={param.ds_id} numel={param.numel()}" | null |
10,484 | def debug_param2name(param):
if param in param_names:
return param_names[param]
else:
return "unknown"
def debug_param2name_id_shape_status(param):
return f"name={debug_param2name(param)} id={param.ds_id} shape={param.data.shape} status={param.ds_status}" | null |
10,485 | fcntl = None
fh = None
The provided code snippet includes necessary dependencies for implementing the `printflock` function. Write a Python function `def printflock(*msgs)` to solve the following problem:
For printing messages for all concurrent gpus w/o getting interleaved text. This is useful when debugging issues w... | For printing messages for all concurrent gpus w/o getting interleaved text. This is useful when debugging issues where multi-gpus don't sync. 1. Enable the force debug in say partitioning and zero3 files 2. Override the usual versions with :: def print_rank_0(message, debug=False, force=False): rank = deepspeed.comm.ge... |
10,486 | fh = None
The provided code snippet includes necessary dependencies for implementing the `log_rank_file` function. Write a Python function `def log_rank_file(rank, *msgs)` to solve the following problem:
Print to a log file of the given rank This is useful for debugging hanging in sync processes. Here is a possible wo... | Print to a log file of the given rank This is useful for debugging hanging in sync processes. Here is a possible workflow: 1. Enable the force debug in say partitioning and zero3 files 2. Override the usual versions of print_rank_0 in those files with :: def print_rank_0(message, debug=False, force=False): rank = deeps... |
10,487 |
def print_backward_tensors(tensor):
def _print_bwd_tensors(grad_fn):
print(f"Backward tensors in {grad_fn}")
for funcs in grad_fn.next_functions:
if funcs[0]:
try:
tensor = getattr(funcs[0], 'variable')
print(funcs[0])
... | null |
10,488 | import math
from deepspeed.utils import log_dist
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "%s ... | null |
10,489 | import math
from deepspeed.utils import log_dist
def calc_bw_log(comm_op, size, duration):
import deepspeed.comm as dist
n = dist.get_world_size()
tput = 0
busbw = 0
if comm_op == "all_to_all_single":
tput = (size / duration)
busbw = (size / duration) * ((n - 1) / n)
elif comm_... | null |
10,490 | import time
import torch
from numpy import mean
from deepspeed.utils.logging import log_dist
from deepspeed import comm as dist
The provided code snippet includes necessary dependencies for implementing the `trim_mean` function. Write a Python function `def trim_mean(data, trim_percent)` to solve the following problem... | Compute the trimmed mean of a list of numbers. Args: data (list): List of numbers. trim_percent (float): Percentage of data to trim. Returns: float: Trimmed mean. |
10,491 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
class DeprecatedException(Exception):
pass
The provided code snippet includes necessary dependencies for implementing the `initialize` function. Write a Python function `def initializ... | Deprecated function. Retained to inform the users. |
10,492 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
def _ensure_divisibility(numerator, denominator):
"""Ensure that numerator is divisible by the denominator."""
assert numerator % denominator == 0, '{} is not divisible by {}'.forma... | Initialize model data parallel groups. Arguments: model_parallel_size: number of GPUs used to parallelize model. Returns: Tuple of data parallel group and model parallel group Let's say we have a total of 8 GPUs denoted by g0 ... g7 and we use 2 GPUs to parallelize the model. The present function will create 4 model pa... |
10,493 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
_EXPERT_PARALLEL_GROUP = {}
_EXPERT_DATA_PARALLEL_GROUP = {}
def _ensure_divisibility(numerator, denominator):
"""Ensure that numerator is divisible by the denominator."""
assert nu... | Create expert and data parallel groups. Note: Caller of this function is responsible to check if the groups already exist. Example - E + D parallel world_size = 16 expert_parallel_size = 2 # number of experts in same group expert_data_parallel_group = [0,2,4,6,8,10,12,14], [1,3,5,7,9,11,13,15] - all reduce is only on M... |
10,494 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
_EXPERT_PARALLEL_GROUP = {}
_EXPERT_DATA_PARALLEL_GROUP = {}
expert_tensor_parallel_world_size = 1
def _ensure_divisibility(numerator, denominator):
"""Ensure that numerator is divisibl... | Create expert and data parallel groups based on MPU (model parallel) group. Note: Caller of this function is responsible to check if the groups already exist. Example - E + M + D parallel world_size = 16 model_degree = 2 expert_degree = 4 # number of experts in same group mp_group = [0, 1], [2,3], [4,5] ... data_parall... |
10,495 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
def _get_max_expert_size_name():
"""Get the name of the group with max. ep_size"""
return f'ep_size_{_get_max_expert_size()}'
def _get_expert_parallel_group(group_name):
"""Get ... | Get the max expert parallel size. |
10,496 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
_EXPERT_PARALLEL_GROUP = {}
The provided code snippet includes necessary dependencies for implementing the `_get_expert_parallel_group_dict` function. Write a Python function `def _get_exp... | Get the expert parallel group dict. |
10,497 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
_EXPERT_DATA_PARALLEL_GROUP = {}
The provided code snippet includes necessary dependencies for implementing the `_get_expert_data_parallel_group_dict` function. Write a Python function `de... | Get the expert data parallel group dict. |
10,498 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
def _get_data_parallel_group():
def _get_broadcast_src_rank():
return dist.get_global_rank(_get_data_parallel_group(), 0) | null |
10,499 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
def _get_expert_data_parallel_group(group_name):
"""Get the expert data parallel group the caller rank belongs to."""
assert group_name in _EXPERT_DATA_PARALLEL_GROUP, \
'ex... | null |
10,500 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
def _get_expert_data_parallel_group(group_name):
"""Get the expert data parallel group the caller rank belongs to."""
assert group_name in _EXPERT_DATA_PARALLEL_GROUP, \
'ex... | Return world size for the expert data parallel group. |
10,501 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
def _get_expert_parallel_group(group_name):
"""Get the expert parallel group the caller rank belongs to."""
assert group_name in _EXPERT_PARALLEL_GROUP, \
'expert parallel g... | Return my rank for the expert parallel group. |
10,502 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
def _get_expert_parallel_world_size(group_name):
"""Return world size for the expert parallel group."""
return dist.get_world_size(group=_get_expert_parallel_group(group_name))
The... | Calculate the global rank corresponding to a local rank zero in the expert parallel group. |
10,503 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
def _get_expert_data_parallel_group(group_name):
"""Get the expert data parallel group the caller rank belongs to."""
assert group_name in _EXPERT_DATA_PARALLEL_GROUP, \
'ex... | Return my rank for the expert data parallel group. |
10,504 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
mpu = None
def _get_data_parallel_group():
"""Get the data parallel group the caller rank belongs to."""
assert dist.is_initialized(), \
'dist is not initialized'
global... | Return world size for the data parallel group. |
10,505 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
mpu = None
The provided code snippet includes necessary dependencies for implementing the `_get_model_parallel_world_size` function. Write a Python function `def _get_model_parallel_world_... | Return world size for the model parallel group. |
10,506 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
mpu = None
def _get_data_parallel_group():
"""Get the data parallel group the caller rank belongs to."""
assert dist.is_initialized(), \
'dist is not initialized'
global... | Return my rank for the data parallel group. |
10,507 | from deepspeed import comm as dist
from deepspeed.utils import log_dist
from deepspeed.utils.exceptions import DeprecatedException
expert_tensor_parallel_world_size = 1
def _get_expert_model_parallel_world_size():
global expert_tensor_parallel_world_size
return expert_tensor_parallel_world_size | null |
10,508 | import types
from deepspeed.utils import get_full_hp_param, get_hp_fragment_mapping
def _init_lp_to_hp_mapping(lp_param_list, partition_start, partition_size, dp_group):
def link_hp_params(lp_param_list,
flat_hp_partition,
partition_start,
partition_size,
... | null |
10,509 | import torch
try:
import torch
_torch_available = True
except ImportError:
_torch_available = False
try:
from torch.hub import _get_torch_home
torch_cache_home = _get_torch_home()
except ImportError:
torch_cache_home = os.path.expanduser(
os.getenv("TORCH_HOME", os.path.join(os.gete... | decorator that causes an NVTX range to be recorded for the duration of the function call. |
10,510 | import torch
from dataclasses import dataclass
from deepspeed import comm as dist
try:
import torch
_torch_available = True
except ImportError:
_torch_available = False
try:
from torch.hub import _get_torch_home
torch_cache_home = _get_torch_home()
except ImportError:
torch_cache_home = os.... | null |
10,511 | import torch
from dataclasses import dataclass
from deepspeed import comm as dist
class fragment_address:
class tensor_fragment:
def update_hp(self):
def update_lp(self):
def get_optim_state_fragment(self, key):
def get_hp_fragment_address(self):
def get_optim_state_keys(self):
try:
import... | null |
10,512 | import os
import torch
import time
import deepspeed
import argparse
from transformers import pipeline
def print_latency(latency_set, title, warmup=3):
# trim warmup queries
latency_set = list(latency_set)
latency_set = latency_set[warmup:]
count = len(latency_set)
if count > 0:
latency_set.... | null |
10,513 | import os
import re
import argparse
import pandas as pd
def get_branch(file_path):
match = re.match(r".*\/(.*)\.log", file_path)
if match is None:
return False
else:
return match.groups()[0] | null |
10,514 | import os
import re
import argparse
import pandas as pd
def get_benchmark_params(root_dir, file_path):
match = re.match(
rf"{root_dir}\/(.+?)_(fp\d+)_(true|false)_(true|false)_(\d+)gpus_v(\d+)\/",
file_path,
)
if match is None:
return False
else:
model, dtype, graphs, ke... | null |
10,515 | import os
import re
import argparse
import pandas as pd
def get_perf_data(file_content):
matches = re.findall(r"\s+(.+?)\sLatency:\s+(\d+\.\d+)\sms", file_content)
if matches is []:
return False
else:
return {f"latency-{key}": float(val) for key, val in matches} | null |
10,516 | import os
import re
import argparse
import pandas as pd
def get_generated_text(file_content, gen_text_n):
file_content = file_content.replace("\n", " ")
file_content = file_content.replace("\t", " ")
matches = re.findall(r"RESPONSE\s(\d+):\s+[-]{30}\s+(.+?)\s+[-]{30}", file_content)
if len(matches) != ... | null |
10,517 | import os
import re
import argparse
import pandas as pd
def get_error(file_content):
matches = re.findall(r"Error:\s+(.+?)\n", file_content)
if matches is []:
return False
else:
return {f"error": val for val in matches} | null |
10,518 | import torch
import time
import deepspeed
import argparse
from transformers import pipeline
print(args.model, args.max_tokens, args.dtype)
print(responses[0:3])
def print_latency(latency_set, title, warmup=3):
# trim warmup queries
latency_set = latency_set[warmup:]
count = len(latency_set)
if count > ... | null |
10,519 | import torch
import os
import math
import argparse
from benchmarks.communication.constants import *
global dist
def init_torch_distributed(backend):
global dist
import torch.distributed as dist
torch.distributed.init_process_group(backend)
local_rank = int(os.environ['LOCAL_RANK'])
torch.cuda.set_de... | null |
10,520 | import torch
import os
import math
import argparse
from benchmarks.communication.constants import *
global dist
def print_rank_0(message):
if dist.get_rank() == 0:
print(message)
def print_header(args, comm_op):
if comm_op == 'pt2pt':
world_size = 2
else:
world_size = dist.get_world... | null |
10,521 | import torch
import os
import math
import argparse
from benchmarks.communication.constants import *
global dist
def print_rank_0(message):
if dist.get_rank() == 0:
print(message)
def get_bw(comm_op, size, duration, args):
n = dist.get_world_size()
tput = 0
busbw = 0
if comm_op == "all_to_al... | null |
10,522 | import torch
import os
import math
import argparse
from benchmarks.communication.constants import *
def get_metric_strings(args, tput, busbw, duration):
duration_ms = duration * 1e3
duration_us = duration * 1e6
tput = f'{tput / 1e9:.3f}'
busbw = f'{busbw /1e9:.3f}'
if duration_us < 1e3 or args.raw... | null |
10,523 | import torch
import os
import math
import argparse
from benchmarks.communication.constants import *
global dist
def sync_all():
torch.cuda.synchronize()
dist.barrier() | null |
10,524 | import torch
import os
import math
import argparse
from benchmarks.communication.constants import *
global dist
def _element_size(dtype):
"""
Returns the element size for a dtype, in bytes
"""
if not isinstance(dtype, torch.dtype):
raise RuntimeError(f'expected torch.dtype, but got {type(dtype)}... | null |
10,525 | import torch
import os
import math
import argparse
from benchmarks.communication.constants import *
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, ... | null |
10,526 | import torch
import os
import math
import argparse
from benchmarks.communication.constants import *
def benchmark_parser():
parser = argparse.ArgumentParser()
parser.add_argument("--local_rank", type=int)
parser.add_argument("--trials",
type=int,
default=DEFA... | null |
10,527 | import torch
from benchmarks.communication.utils import *
from benchmarks.communication.constants import *
import time
def timed_broadcast(input, args):
if args.dist == 'torch':
import torch.distributed as dist
elif args.dist == 'deepspeed':
import deepspeed.comm as dist
sync_all()
# War... | null |
10,528 | from benchmarks.communication.utils import *
from benchmarks.communication.constants import *
import time
def timed_all_reduce(input, args):
if args.dist == 'torch':
import torch.distributed as dist
elif args.dist == 'deepspeed':
import deepspeed.comm as dist
sync_all()
# Warmups, establ... | null |
10,529 | from benchmarks.communication.utils import *
from benchmarks.communication.constants import *
import time
def timed_pt2pt(input, args):
if args.dist == 'torch':
import torch.distributed as dist
elif args.dist == 'deepspeed':
import deepspeed.comm as dist
sync_all()
# Warmups, establish c... | null |
10,530 | from benchmarks.communication.utils import *
from benchmarks.communication.constants import *
import time
def timed_all_to_all(input, output, args):
if args.dist == 'torch':
import torch.distributed as dist
elif args.dist == 'deepspeed':
import deepspeed.comm as dist
sync_all()
# Warmups... | null |
10,531 | from benchmarks.communication.utils import *
from benchmarks.communication.constants import *
import time
def timed_all_gather(input, output, args):
if args.dist == 'torch':
import torch.distributed as dist
elif args.dist == 'deepspeed':
import deepspeed.comm as dist
sync_all()
# Warmups... | null |
10,534 | from __future__ import annotations
import subprocess
import sys
def err(s: str) -> None:
print(s, file=sys.stderr) | null |
10,535 | import os
import re
import shutil
from distutils.core import Command
from pathlib import Path
from setuptools import find_packages, setup
deps = {b: a for a, b in (re.findall(r"^(([^!=<>~ ]+)(?:[!=<>~ ].*)?$)", x)[0] for x in _deps)}
def deps_list(*pkgs):
return [deps[pkg] for pkg in pkgs] | null |
10,536 | import functools
import gc
import inspect
import json
import os
import pickle
import re
import warnings
from collections.abc import Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
import h5py
import numpy as np
import tensorflow as tf
from tensorflow.python.... | null |
10,537 | import functools
import gc
import inspect
import json
import os
import pickle
import re
import warnings
from collections.abc import Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
import h5py
import numpy as np
import tensorflow as tf
from tensorflow.python.... | Decorate a Keras Layer class to support Keras serialization. This is done by: 1. Adding a `transformers_config` dict to the Keras config dictionary in `get_config` (called by Keras at serialization time. 2. Wrapping `__init__` to accept that `transformers_config` dict (passed by Keras at deserialization time) and conve... |
10,538 | import functools
import gc
import inspect
import json
import os
import pickle
import re
import warnings
from collections.abc import Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
import h5py
import numpy as np
import tensorflow as tf
from tensorflow.python.... | Decorator that processes the inputs to a Keras layer, passing them to the layer as keyword arguments. This enables downstream use of the inputs by their variable name, even if they arrive packed as a dictionary in the first input (common case in Keras). Args: func (`callable`): The callable function of the TensorFlow m... |
10,539 | import functools
import gc
import inspect
import json
import os
import pickle
import re
import warnings
from collections.abc import Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
import h5py
import numpy as np
import tensorflow as tf
from tensorflow.python.... | Splits a model state dictionary in sub-checkpoints so that the final size of each sub-checkpoint does not exceed a given size. The sub-checkpoints are determined by iterating through the `state_dict` in the order of its keys, so there is no optimization made to make each sub-checkpoint as close as possible to the maxim... |
10,540 | import functools
import gc
import inspect
import json
import os
import pickle
import re
import warnings
from collections.abc import Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
import h5py
import numpy as np
import tensorflow as tf
from tensorflow.python.... | This is the same as `load_tf_weights` but for a sharded checkpoint. Detect missing and unexpected layers and load the TF weights from the shard file accordingly to their names and shapes. This load is performed efficiently: each checkpoint shard is loaded one by one in RAM and deleted after being loaded in the model. A... |
10,541 | import functools
import gc
import inspect
import json
import os
import pickle
import re
import warnings
from collections.abc import Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
import h5py
import numpy as np
import tensorflow as tf
from tensorflow.python.... | r""" This function aims to reduce the embeddings in case new_num_tokens < old_num_tokens or to pad with -1 in case new_num_tokens > old_num_tokens. A mask is also computed in order to know which weight in the embeddings should be kept or not. Example: - if new_num_tokens=5 and old_num_tokens=4 and old_embeddings=[w1,w2... |
10,542 | import functools
import gc
import inspect
import json
import os
import pickle
import re
import warnings
from collections.abc import Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
import h5py
import numpy as np
import tensorflow as tf
from tensorflow.python.... | Creates a `tf.initializers.TruncatedNormal` with the given range. Args: initializer_range (*float*, defaults to 0.02): Standard deviation of the initializer range. Returns: `tf.initializers.TruncatedNormal`: The truncated normal initializer. |
10,543 | import functools
import importlib.util
import json
import numbers
import os
import pickle
import shutil
import sys
import tempfile
from dataclasses import asdict
from pathlib import Path
from typing import TYPE_CHECKING, Dict, Optional
import numpy as np
from . import __version__ as version
from .utils import flatten_d... | null |
10,544 | import functools
import importlib.util
import json
import numbers
import os
import pickle
import shutil
import sys
import tempfile
from dataclasses import asdict
from pathlib import Path
from typing import TYPE_CHECKING, Dict, Optional
import numpy as np
from . import __version__ as version
from .utils import flatten_d... | null |
10,545 | import functools
import importlib.util
import json
import numbers
import os
import pickle
import shutil
import sys
import tempfile
from dataclasses import asdict
from pathlib import Path
from typing import TYPE_CHECKING, Dict, Optional
import numpy as np
from . import __version__ as version
from .utils import flatten_d... | null |
10,546 | import functools
import importlib.util
import json
import numbers
import os
import pickle
import shutil
import sys
import tempfile
from dataclasses import asdict
from pathlib import Path
from typing import TYPE_CHECKING, Dict, Optional
import numpy as np
from . import __version__ as version
from .utils import flatten_d... | null |
10,547 | import functools
import importlib.util
import json
import numbers
import os
import pickle
import shutil
import sys
import tempfile
from dataclasses import asdict
from pathlib import Path
from typing import TYPE_CHECKING, Dict, Optional
import numpy as np
from . import __version__ as version
from .utils import flatten_d... | null |
10,548 | import functools
import importlib.util
import json
import numbers
import os
import pickle
import shutil
import sys
import tempfile
from dataclasses import asdict
from pathlib import Path
from typing import TYPE_CHECKING, Dict, Optional
import numpy as np
from . import __version__ as version
from .utils import flatten_d... | null |
10,549 | import functools
import importlib.util
import json
import numbers
import os
import pickle
import shutil
import sys
import tempfile
from dataclasses import asdict
from pathlib import Path
from typing import TYPE_CHECKING, Dict, Optional
import numpy as np
from . import __version__ as version
from .utils import flatten_d... | null |
10,550 | import functools
import importlib.util
import json
import numbers
import os
import pickle
import shutil
import sys
import tempfile
from dataclasses import asdict
from pathlib import Path
from typing import TYPE_CHECKING, Dict, Optional
import numpy as np
from . import __version__ as version
from .utils import flatten_d... | null |
10,551 | import functools
import importlib.util
import json
import numbers
import os
import pickle
import shutil
import sys
import tempfile
from dataclasses import asdict
from pathlib import Path
from typing import TYPE_CHECKING, Dict, Optional
import numpy as np
from . import __version__ as version
from .utils import flatten_d... | null |
10,552 | import inspect
from typing import Callable, List, Optional, Set, Tuple, Union
import torch
from packaging import version
from torch import _softmax_backward_data, nn
from .utils import logging
is_torch_less_than_1_8 = parsed_torch_version_base < version.parse("1.8.0")
The provided code snippet includes necessary depen... | A function that performs integer division across different versions of PyTorch. |
10,553 | import inspect
from typing import Callable, List, Optional, Set, Tuple, Union
import torch
from packaging import version
from torch import _softmax_backward_data, nn
from .utils import logging
is_torch_less_than_1_11 = parsed_torch_version_base < version.parse("1.11")
The provided code snippet includes necessary depen... | A function that calls the internal `_softmax_backward_data` PyTorch method and that adjusts the arguments according to the torch version detected. |
10,554 | import inspect
from typing import Callable, List, Optional, Set, Tuple, Union
import torch
from packaging import version
from torch import _softmax_backward_data, nn
from .utils import logging
def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: int = 0) -> nn.Linear:
"""
Prune a linear layer ... | Prune a Conv1D or linear layer to keep only entries in index. Used to remove heads. Args: layer (`Union[torch.nn.Linear, Conv1D]`): The layer to prune. index (`torch.LongTensor`): The indices to keep in the layer. dim (`int`, *optional*): The dimension on which to keep the indices. Returns: `torch.nn.Linear` or [`~pyto... |
10,555 | import inspect
from typing import Callable, List, Optional, Set, Tuple, Union
import torch
from packaging import version
from torch import _softmax_backward_data, nn
from .utils import logging
The provided code snippet includes necessary dependencies for implementing the `apply_chunking_to_forward` function. Write a P... | This function chunks the `input_tensors` into smaller input tensor parts of size `chunk_size` over the dimension `chunk_dim`. It then applies a layer `forward_fn` to each chunk independently to save memory. If the `forward_fn` is independent across the `chunk_dim` this function will yield the same result as directly ap... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.