id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
141,314
import os import sys from numbers import Number import atexit import torch from metaseq.logging.meters import AverageMeter from metaseq.logging.progress_bar.base_progress_bar import BaseProgressBar, logger _tensorboard_writers = {} def _close_writers(): for w in _tensorboard_writers.values(): w.close()
null
141,315
import json from collections import OrderedDict from contextlib import contextmanager from metaseq.logging.progress_bar.base_progress_bar import ( BaseProgressBar, logger, format_stat, ) from metaseq.utils import get_precise_epoch def rename_logger(logger, new_name): old_name = logger.name if new_n...
null
141,316
import logging from collections import OrderedDict from numbers import Number import torch from metaseq.logging.meters import AverageMeter, TimeMeter, StopwatchMeter class AverageMeter(Meter): def __init__(self, round: Optional[int] = None): def reset(self): def update(self, val, n=1): def state_di...
null
141,317
import contextlib import logging import subprocess import uuid from collections import defaultdict from typing import Callable, List, Optional, Dict from .meters import ( OrderedDict, MetersDict, AverageMeter, TimeMeter, StopwatchMeter, Meter, ) def get_active_aggregators() -> List[MetersDict]: ...
Log a scalar value. Args: key (str): name of the field to log value (float): value to log weight (float): weight that this value contributes to the average. A weight of 0 will always log the latest value. priority (int): smaller values are logged earlier in the output round (Optional[int]): number of digits to round to...
141,318
import contextlib import logging import subprocess import uuid from collections import defaultdict from typing import Callable, List, Optional, Dict from .meters import ( OrderedDict, MetersDict, AverageMeter, TimeMeter, StopwatchMeter, Meter, ) def get_active_aggregators() -> List[MetersDict]: ...
Log a scalar value derived from other meters. Args: key (str): name of the field to log fn (Callable[[MetersDict], float]): function that takes a single argument *meters* and returns the derived value priority (int): smaller values are logged earlier in the output
141,319
import contextlib import logging import subprocess import uuid from collections import defaultdict from typing import Callable, List, Optional, Dict from .meters import ( OrderedDict, MetersDict, AverageMeter, TimeMeter, StopwatchMeter, Meter, ) def reset() -> None: """Reset all metrics aggr...
Log the rate of some quantity per second. Args: key (str): name of the field to log value (float): value to log priority (int): smaller values are logged earlier in the output round (Optional[int]): number of digits to round to when displaying
141,320
import contextlib import logging import subprocess import uuid from collections import defaultdict from typing import Callable, List, Optional, Dict from .meters import ( OrderedDict, MetersDict, AverageMeter, TimeMeter, StopwatchMeter, Meter, ) def get_active_aggregators() -> List[MetersDict]: ...
Log using a custom Meter. Any extra *args* or *kwargs* will be passed through to the Meter's *update* method. Args: new_meter_fn (Callable[[], Meter]): function that returns a new Meter instance key (str): name of the field to log priority (int): smaller values are logged earlier in the output
141,321
import contextlib import logging import subprocess import uuid from collections import defaultdict from typing import Callable, List, Optional, Dict from .meters import ( OrderedDict, MetersDict, AverageMeter, TimeMeter, StopwatchMeter, Meter, ) def reset() -> None: """Reset all metrics aggr...
Reset Meter instance aggregated under a given *name* and *key*.
141,322
import contextlib import logging import subprocess import uuid from collections import defaultdict from typing import Callable, List, Optional, Dict from .meters import ( OrderedDict, MetersDict, AverageMeter, TimeMeter, StopwatchMeter, Meter, ) _aggregators = OrderedDict() The provided code sn...
Get a single smoothed value. Raises: KeyError: if no metrics have been logged under *name* and *key*.
141,323
import contextlib import logging import subprocess import uuid from collections import defaultdict from typing import Callable, List, Optional, Dict from .meters import ( OrderedDict, MetersDict, AverageMeter, TimeMeter, StopwatchMeter, Meter, ) _aggregators = OrderedDict() def state_dict(): ...
null
141,324
import contextlib import logging import subprocess import uuid from collections import defaultdict from typing import Callable, List, Optional, Dict from .meters import ( OrderedDict, MetersDict, AverageMeter, TimeMeter, StopwatchMeter, Meter, ) _aggregators = OrderedDict() class MetersDict(Ord...
null
141,325
import contextlib import logging import subprocess import uuid from collections import defaultdict from typing import Callable, List, Optional, Dict from .meters import ( OrderedDict, MetersDict, AverageMeter, TimeMeter, StopwatchMeter, Meter, ) def nvidia_smi_gpu_memory_stats(): """ Par...
null
141,326
import contextlib import functools import logging import math import os import re import sys import time from concurrent.futures import ThreadPoolExecutor from itertools import chain from typing import Any, Dict, List import torch import torch.distributed as dist from omegaconf import OmegaConf from metaseq import chec...
null
141,327
import contextlib import functools import logging import math import os import re import sys import time from concurrent.futures import ThreadPoolExecutor from itertools import chain from typing import Any, Dict, List import torch import torch.distributed as dist from omegaconf import OmegaConf from metaseq import chec...
null
141,328
import contextlib import functools import logging import math import os import re import sys import time from concurrent.futures import ThreadPoolExecutor from itertools import chain from typing import Any, Dict, List import torch import torch.distributed as dist from omegaconf import OmegaConf from metaseq import chec...
null
141,329
import fnmatch import json import logging import os import shutil import tarfile import tempfile from functools import partial, wraps from hashlib import sha256 from io import open logger = logging.getLogger(__name__) def cached_path(url_or_filename, cache_dir=None): """ Given something that might be a URL (or...
null
141,331
import os import math import logging from typing import Optional import numpy as np import torch from metaseq.data import data_utils from metaseq.distributed import utils as distributed_utils import time from typing import Union, List, Iterable, Tuple, TypedDict, Literal from multiprocessing import Array, Lock from con...
Create a function that returns random numbers based on seed. Block calls to numpy's integers function because it has high overhead.
141,332
import os import math import logging from typing import Optional import numpy as np import torch from metaseq.data import data_utils from metaseq.distributed import utils as distributed_utils import time from typing import Union, List, Iterable, Tuple, TypedDict, Literal from multiprocessing import Array, Lock from con...
Mimics sample-break-mode eos i.e. 1 example per sequence without any packing. When multiple examples are packed into a single sequence, example tokens would attend to tokens in neighbouring examples, which may be undesirable. This mode can avoid that. Since there is no packing, this mode is considerably slower. We roun...
141,333
import os import math import logging from typing import Optional import numpy as np import torch from metaseq.data import data_utils from metaseq.distributed import utils as distributed_utils import time from typing import Union, List, Iterable, Tuple, TypedDict, Literal from multiprocessing import Array, Lock from con...
Mimics sample-break-mode complete
141,334
import os import math import logging from typing import Optional import numpy as np import torch from metaseq.data import data_utils from metaseq.distributed import utils as distributed_utils import time from typing import Union, List, Iterable, Tuple, TypedDict, Literal from multiprocessing import Array, Lock from con...
null
141,335
import os import math import logging from typing import Optional import numpy as np import torch from metaseq.data import data_utils from metaseq.distributed import utils as distributed_utils import time from typing import Union, List, Iterable, Tuple, TypedDict, Literal from multiprocessing import Array, Lock from con...
Sample break mode = None. (Pre-Training default).
141,336
import numpy as np from metaseq.data import data_utils from . import BaseWrapperDataset class TruncateDataset(BaseWrapperDataset): def __init__(self, dataset, truncation_length): def __getitem__(self, index): def sizes(self): def __len__(self): class RandomCropDataset(TruncateDataset): def __in...
null
141,337
import contextlib import itertools import logging import os import re import numpy as np from metaseq import utils from metaseq.file_io import PathManager logger = logging.getLogger(__name__) class ConcatDataset(BaseDataset): def cumsum(sequence, sample_ratios): r, s = [], 0 for e, ratio in zip(seq...
A helper function for loading indexed datasets. Args: path (str): path to indexed dataset (e.g., 'data-bin/train') dictionary (~metaseq.data.Dictionary): data dictionary dataset_impl (str, optional): which dataset implementation to use. If not provided, it will be inferred automatically. For legacy indexed data we use ...
141,338
import contextlib import itertools import logging import os import re import numpy as np from metaseq import utils from metaseq.file_io import PathManager The provided code snippet includes necessary dependencies for implementing the `numpy_seed` function. Write a Python function `def numpy_seed(seed, *addl_seeds)` to...
Context manager which seeds the NumPy PRNG with the specified seed and restores the state afterward
141,339
import contextlib import itertools import logging import os import re import numpy as np from metaseq import utils from metaseq.file_io import PathManager def collect_filtered(function, iterable, filtered): def _filter_by_size_dynamic(indices, size_fn, max_positions, raise_exception=False): def compare_leq(a, b): ...
null
141,340
import contextlib import itertools import logging import os import re import numpy as np from metaseq import utils from metaseq.file_io import PathManager The provided code snippet includes necessary dependencies for implementing the `batch_by_size` function. Write a Python function `def batch_by_size( indices, ...
Yield mini-batches of indices bucketed by size. Batches may contain sequences of different lengths. Args: indices (List[int]): ordered list of dataset indices num_tokens_fn (callable): function that returns the number of tokens at a given index num_tokens_vec (List[int], optional): precomputed vector of the number of t...
141,341
import contextlib import itertools import logging import os import re import numpy as np from metaseq import utils from metaseq.file_io import PathManager def post_process(sentence: str, symbol: str): if symbol == "sentencepiece": sentence = sentence.replace(" ", "").replace("\u2581", " ").strip() elif...
null
141,342
import contextlib import itertools import logging import os import re import numpy as np from metaseq import utils from metaseq.file_io import PathManager def _find_extra_valid_paths(dataset_path: str) -> set: paths = utils.split_paths(dataset_path) all_valid_paths = set() for sub_dir in paths: if "...
Raises if there are paths matching 'valid*[0-9].*' which are not combined or ignored.
141,343
import numpy as np import torch from typing import List, Optional, Tuple from .document_to_sequence import DocumentToSequenceDataset def span_intersection(left: Tuple[int, int], right: Tuple[int, int]) -> bool: left_x, left_y = left right_x, right_y = right return max(left_x, right_x) < min(left_y, right_y...
null
141,344
import numpy as np import torch from typing import List, Optional, Tuple from .document_to_sequence import DocumentToSequenceDataset def overlaps(span_1: Tuple[int, int], span_2: Tuple[int, int]) -> bool: # Check if two spans overlap return not (span_1[1] <= span_2[0] or span_1[0] >= span_2[1]) def calculate_ov...
null
141,345
import itertools import logging import math import operator import os import queue import time from threading import Thread from typing import Callable, Optional import numpy as np import torch from metaseq.distributed import utils as distributed_utils from metaseq.data import data_utils from metaseq.data.document_to_s...
null
141,346
from typing import Optional import numpy as np import torch import math The provided code snippet includes necessary dependencies for implementing the `yield_src_tgt_blocks` function. Write a Python function `def yield_src_tgt_blocks(iterable, block_size, drop_last, padding_idx)` to solve the following problem: Packs ...
Packs multiple examples together in a block
141,347
from typing import Optional import numpy as np import torch import math The provided code snippet includes necessary dependencies for implementing the `yield_src_tgt_single_sentences_pad_8` function. Write a Python function `def yield_src_tgt_single_sentences_pad_8(iterable, block_size, drop_last, padding_idx)` to sol...
Mimics sample-break-mode eos i.e. 1 example per sequence without any packing. When multiple examples are packed into a single sequence, example tokens would attend to tokens in neighbouring examples, which may be undesirable. This mode can avoid that. Since there is no packing, this mode is considerably slower. We roun...
141,348
from collections import OrderedDict import torch from torch.utils.data.dataloader import default_collate from . import BaseDataset The provided code snippet includes necessary dependencies for implementing the `_flatten` function. Write a Python function `def _flatten(dico, prefix=None)` to solve the following problem...
Flatten a nested dictionary.
141,349
from collections import OrderedDict import torch from torch.utils.data.dataloader import default_collate from . import BaseDataset The provided code snippet includes necessary dependencies for implementing the `_unflatten` function. Write a Python function `def _unflatten(dico)` to solve the following problem: Unflatt...
Unflatten a flattened dictionary into a nested dictionary.
141,350
import math from typing import Optional import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `yield_single_sentences_pad_8` function. Write a Python function `def yield_single_sentences_pad_8(iterable, block_size, drop_last, padding_idx)` to solve the following...
Mimics sample-break-mode eos i.e. 1 example per sequence without any packing. When multiple examples are packed into a single sequence, example tokens would attend to tokens in neighbouring examples, which may be undesirable. This mode can avoid that. Since there is no packing, this mode is considerably slower. We roun...
141,351
import math from typing import Optional import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `yield_doc_blocks` function. Write a Python function `def yield_doc_blocks(iterable, block_size, drop_last, padding_idx)` to solve the following problem: Mimics sample-...
Mimics sample-break-mode complete
141,352
import math from typing import Optional import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `yield_token_blocks` function. Write a Python function `def yield_token_blocks(iterable, block_size, drop_last, padding_idx)` to solve the following problem: Sample bre...
Sample break mode = None. (Pre-Training default).
141,353
import numpy as np import torch from . import BaseDataset, data_utils def collate(samples, pad_idx, eos_idx, fixed_pad_length=None, pad_to_bsz=None): if len(samples) == 0: return {} def merge(key, is_list=False): if is_list: res = [] for i in range(len(samples[0][key]))...
null
141,356
import json from functools import lru_cache class Encoder: def __init__(self, encoder, bpe_merges, errors="replace"): self.encoder = encoder self.decoder = {v: k for k, v in self.encoder.items()} self.errors = errors # how to handle errors in decoding self.byte_encoder = bytes_to_un...
null
141,357
import shutil import struct from functools import lru_cache from typing import Union import numpy as np import torch from metaseq.dataclass.constants import DATASET_IMPL_CHOICES from metaseq.file_io import PathManager from . import BaseDataset DATASET_IMPL_CHOICES = ChoiceEnum(["raw", "lazy", "cached", "mmap", "fasta"...
null
141,358
import shutil import struct from functools import lru_cache from typing import Union import numpy as np import torch from metaseq.dataclass.constants import DATASET_IMPL_CHOICES from metaseq.file_io import PathManager from . import BaseDataset def best_fitting_int_dtype( max_int_to_represent, ) -> Union[np.uint16, ...
null
141,359
import shutil import struct from functools import lru_cache from typing import Union import numpy as np import torch from metaseq.dataclass.constants import DATASET_IMPL_CHOICES from metaseq.file_io import PathManager from . import BaseDataset class IndexedDataset(BaseDataset): """Loader for TorchNet IndexedDataset...
null
141,360
import shutil import struct from functools import lru_cache from typing import Union import numpy as np import torch from metaseq.dataclass.constants import DATASET_IMPL_CHOICES from metaseq.file_io import PathManager from . import BaseDataset def read_longs(f, n): a = np.empty(n, dtype=np.int64) f.readinto(a)...
null
141,361
import shutil import struct from functools import lru_cache from typing import Union import numpy as np import torch from metaseq.dataclass.constants import DATASET_IMPL_CHOICES from metaseq.file_io import PathManager from . import BaseDataset def write_longs(f, a): f.write(np.array(a, dtype=np.int64))
null
141,362
import shutil import struct from functools import lru_cache from typing import Union import numpy as np import torch from metaseq.dataclass.constants import DATASET_IMPL_CHOICES from metaseq.file_io import PathManager from . import BaseDataset _code_to_dtype = { 1: np.uint8, 2: np.int8, 3: np.int16, 4: ...
null
141,363
import shutil import struct from functools import lru_cache from typing import Union import numpy as np import torch from metaseq.dataclass.constants import DATASET_IMPL_CHOICES from metaseq.file_io import PathManager from . import BaseDataset def _warmup_mmap_file(path): with open(path, "rb") as stream: w...
null
141,364
from argparse import Namespace from typing import Union from hydra.core.config_store import ConfigStore from omegaconf import DictConfig from metaseq.dataclass import MetaseqDataclass from metaseq.dataclass.utils import populate_dataclass, merge_with_parent REGISTRIES = {} def populate_dataclass( dataclass: Metase...
null
141,365
import argparse import ast import logging import os import re import time from argparse import Namespace from typing import List, Optional from tokenizers import ByteLevelBPETokenizer import numpy as np import torch from metaseq import checkpoint_utils, tasks from metaseq import utils, distributed_utils from metaseq.da...
null
141,366
import argparse import ast import logging import os import re import time from argparse import Namespace from typing import List, Optional from tokenizers import ByteLevelBPETokenizer import numpy as np import torch from metaseq import checkpoint_utils, tasks from metaseq import utils, distributed_utils from metaseq.da...
null
141,367
import argparse import ast import logging import os import re import time from argparse import Namespace from typing import List, Optional from tokenizers import ByteLevelBPETokenizer import numpy as np import torch from metaseq import checkpoint_utils, tasks from metaseq import utils, distributed_utils from metaseq.da...
null
141,368
import argparse from typing import Callable, List, Optional import torch from metaseq import utils from metaseq.dataclass.configs import ( CheckpointConfig, CommonConfig, CommonEvalConfig, DatasetConfig, DistributedTrainingConfig, EvalLMConfig, GenerationConfig, OptimizationConfig, R...
null
141,369
import math import torch import torch.nn.functional as F from metaseq import metrics, utils from metaseq.criterions import BaseCriterion, register_criterion The provided code snippet includes necessary dependencies for implementing the `nll_loss` function. Write a Python function `def nll_loss(lprobs, target, ignore_i...
Like torch.nn.functional.nll_loss but works for large inputs.
141,370
import argparse from datetime import datetime import functools import logging import math import os import subprocess import sys import time import socket import re from typing import Dict, Optional, Any, List, Tuple, Callable from urllib.parse import urlparse import warnings import numpy as np import torch import torc...
Train the model for one epoch and return validation losses.
141,371
import argparse from datetime import datetime import functools import logging import math import os import subprocess import sys import time import socket import re from typing import Dict, Optional, Any, List, Tuple, Callable from urllib.parse import urlparse import warnings import numpy as np import torch import torc...
null
141,372
import logging import os import sys from argparse import Namespace from itertools import chain import torch from omegaconf import DictConfig from metaseq import checkpoint_utils, distributed_utils, options, utils from metaseq.dataclass.utils import convert_namespace_to_omegaconf from metaseq.logging import metrics, pro...
null
141,373
import os import ast import queue import pkg_resources import random import threading import traceback import torch from flask import Flask, request, jsonify from werkzeug.exceptions import HTTPException from metaseq import options from metaseq.dataclass.configs import MetaseqConfig from metaseq.dataclass.utils import ...
null
141,374
import os import ast import queue import pkg_resources import random import threading import traceback import torch from flask import Flask, request, jsonify from werkzeug.exceptions import HTTPException from metaseq import options from metaseq.dataclass.configs import MetaseqConfig from metaseq.dataclass.utils import ...
null
141,375
import os import ast import queue import pkg_resources import random import threading import traceback import torch from flask import Flask, request, jsonify from werkzeug.exceptions import HTTPException from metaseq import options from metaseq.dataclass.configs import MetaseqConfig from metaseq.dataclass.utils import ...
null
141,376
import os import ast import queue import pkg_resources import random import threading import traceback import torch from flask import Flask, request, jsonify from werkzeug.exceptions import HTTPException from metaseq import options from metaseq.dataclass.configs import MetaseqConfig from metaseq.dataclass.utils import ...
Hosted version of the web UI for generation.
141,377
import os import ast import random import sys import logging import torch from metaseq import options from metaseq.dataclass.configs import MetaseqConfig from metaseq.dataclass.utils import convert_namespace_to_omegaconf from metaseq.distributed import utils as distributed_utils from metaseq.hub_utils import GeneratorI...
Command line interactive.
141,378
import argparse import os import torch import torch.distributed as dist import torch.nn as nn from tokenizers import Tokenizer, ByteLevelBPETokenizer from typing import Any, List, Optional try: torch.classes.load_library(os.environ.get("FT_PATH")) except Exception: raise ImportError( "Please install Fas...
null
141,379
import argparse import os import torch import torch.distributed as dist import torch.nn as nn from tokenizers import Tokenizer, ByteLevelBPETokenizer from typing import Any, List, Optional try: torch.classes.load_library(os.environ.get("FT_PATH")) except Exception: raise ImportError( "Please install Fas...
null
141,380
import argparse import os import torch import torch.distributed as dist import torch.nn as nn from tokenizers import Tokenizer, ByteLevelBPETokenizer from typing import Any, List, Optional def get_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--num-layers", type=int, def...
null
141,381
import socket import logging import sys import os The provided code snippet includes necessary dependencies for implementing the `normalize_newlines` function. Write a Python function `def normalize_newlines(s: str)` to solve the following problem: normalizes new lines, i.e. '\r\n' to '\n' Here is the function: def ...
normalizes new lines, i.e. '\r\n' to '\n'
141,382
import socket import logging import sys import os def build_logger(): logging.basicConfig( format="%(asctime)s | %(levelname)s | %(name)s | %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=os.environ.get("LOGLEVEL", "INFO").upper(), stream=sys.stdout, ) logger = logging.getL...
null
141,383
import datetime as dt import io import logging import os import shutil import types from functools import partial from typing import Any, Dict, IO, List, Optional, Tuple, Union import boto3 import botocore from boto3.s3.transfer import TransferConfig from metaseq.file_io.common import file_lock, get_cache_dir, PathHand...
null
141,384
import logging from hydra.core.config_store import ConfigStore from metaseq.dataclass.configs import MetaseqConfig logger = logging.getLogger(__name__) class MetaseqConfig(MetaseqDataclass): common: CommonConfig = CommonConfig() common_eval: CommonEvalConfig = CommonEvalConfig() distributed_training: Distr...
null
141,386
import multiprocessing import os import pdb import sys def set_trace(): pdb = MultiprocessingPdb() pdb.set_trace(sys._getframe().f_back) def set_trace_rank0(): import metaseq.distributed.utils as distributed_utils if distributed_utils.get_global_rank() == 0: set_trace() else: while...
null
141,387
import uuid from typing import Dict, Optional from torch import Tensor from typing_extensions import Protocol class IncrementalState(object): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.init_incremental_state() def init_incremental_state(self): self._incre...
null
141,388
import os from metaseq.launcher.opt_job_constants import ( TOTAL_TRAIN_TOKENS, TOTAL_WARMUP_TOKENS, MODEL_SIZES, VALID_SUBSETS, ) from metaseq.launcher.sweep import ( hyperparam, get_env_from_args, main as sweep_main, ) def add_extra_options_func(parser): # NOTE we shouldn't add new opti...
null
141,389
import argparse import datetime import os import subprocess from typing import Optional, List, Callable, MutableMapping from urllib.parse import urlparse def get_env_from_args(args): if args.azure: return ComputeEnvs.AZURE elif args.aws: return ComputeEnvs.AWS elif args.fair: return ...
input_args (List[str]): strings to parse, defaults to sys.argv
141,390
import datetime import fnmatch import hashlib import itertools import os import random import shlex import shutil import subprocess import textwrap from collections import OrderedDict from pathlib import Path import metaseq from metaseq.utils import get_random_port from metaseq.launcher.tombyard import tombstones from ...
null
141,391
import time import logging from typing import Dict from urllib.parse import urlparse from torch.distributed.constants import default_pg_timeout from torch.distributed import register_rendezvous_handler, Store, TCPStore, rendezvous RETRIES = 5 COOLDOWN = 0.25 logger = logging.getLogger(__name__) def _create_c10d_store(h...
null
141,392
import time import logging from typing import Dict from urllib.parse import urlparse from torch.distributed.constants import default_pg_timeout from torch.distributed import register_rendezvous_handler, Store, TCPStore, rendezvous class ComplicitStore(Store): def __init__(self, store: Store, world_size: int): ...
null
141,393
import io import logging import os import pickle import random import signal import socket import struct import subprocess from argparse import Namespace from collections import OrderedDict from dataclasses import dataclass from typing import Any, Dict, List, Mapping, Optional import torch import torch.distributed as d...
null
141,394
import io import logging import os import pickle import random import signal import socket import struct import subprocess from argparse import Namespace from collections import OrderedDict from dataclasses import dataclass from typing import Any, Dict, List, Mapping, Optional import torch import torch.distributed as d...
null
141,395
import io import logging import os import pickle import random import signal import socket import struct import subprocess from argparse import Namespace from collections import OrderedDict from dataclasses import dataclass from typing import Any, Dict, List, Mapping, Optional import torch import torch.distributed as d...
Perform an all-to-all operation on a 1D Tensor.
141,396
import io import logging import os import pickle import random import signal import socket import struct import subprocess from argparse import Namespace from collections import OrderedDict from dataclasses import dataclass from typing import Any, Dict, List, Mapping, Optional import torch import torch.distributed as d...
Gathers arbitrary data from all nodes into a list. Similar to :func:`~torch.distributed.all_gather` but for arbitrary Python data. Note that *data* must be picklable and any CUDA tensors will be moved to CPU and returned on CPU as well. Args: data (Any): data from the local worker to be gathered on other workers group:...
141,397
import io import logging import os import pickle import random import signal import socket import struct import subprocess from argparse import Namespace from collections import OrderedDict from dataclasses import dataclass from typing import Any, Dict, List, Mapping, Optional import torch import torch.distributed as d...
AllReduce a dictionary of values across workers. We separately reduce items that are already on the device and items on CPU for better performance. Args: data (Mapping[str, Any]): dictionary of data to all-reduce, but cannot be a nested dictionary device (torch.device): device for the reduction group: group of the coll...
141,398
import gc import logging import os import re import time from collections import defaultdict, OrderedDict from glob import glob from pathlib import Path import torch from tqdm import tqdm from metaseq.distributed.fully_sharded_data_parallel import FSDP as FSDP from metaseq.file_io import load_and_pop_last_optimizer_sta...
null
141,399
import gc import logging import os import re import time from collections import defaultdict, OrderedDict from glob import glob from pathlib import Path import torch from tqdm import tqdm from metaseq.distributed.fully_sharded_data_parallel import FSDP as FSDP from metaseq.file_io import load_and_pop_last_optimizer_sta...
Make it look like a normal LayerNorm
141,400
import gc import logging import os import re import time from collections import defaultdict, OrderedDict from glob import glob from pathlib import Path import torch from tqdm import tqdm from metaseq.distributed.fully_sharded_data_parallel import FSDP as FSDP from metaseq.file_io import load_and_pop_last_optimizer_sta...
null
141,401
import contextlib import logging import os from typing import Optional import torch from metaseq.dataclass.configs import DistributedTrainingConfig from metaseq.distributed import utils as distributed_utils try: from fairscale.nn.data_parallel import FullyShardedDataParallel as FSDP from fairscale.utils.testing...
null
141,402
import contextlib import logging import os from typing import Optional import torch from metaseq.dataclass.configs import DistributedTrainingConfig from metaseq.distributed import utils as distributed_utils logger = logging.getLogger(__name__) try: from fairscale.nn.data_parallel import FullyShardedDataParallel as ...
Helper to wrap layers/modules in FSDP. This falls back to a no-op if fairscale is not available. Args: module (nn.Module): module to (maybe) wrap min_num_params (int, Optional): minimum number of layer params to wrap
141,403
import logging import random import socket import sys from typing import Tuple import numpy as np import torch from torch.profiler.profiler import ( ProfilerActivity, schedule, tensorboard_trace_handler, ) from tqdm import tqdm from metaseq import options from metaseq.dataclass.configs import MetaseqConfig ...
null
141,404
import logging import random import socket import sys from typing import Tuple import numpy as np import torch from torch.profiler.profiler import ( ProfilerActivity, schedule, tensorboard_trace_handler, ) from tqdm import tqdm from metaseq import options from metaseq.dataclass.configs import MetaseqConfig ...
null
141,405
import logging import os from copy import deepcopy from typing import Any, Dict, List, Tuple import fire import torch import torch.nn.functional as F logger: logging.Logger = logging.getLogger("metaseq.scripts.reshard_consolidated") def reshard_unflattened_model_weights( unsharded_weights: Dict[str, torch.Tensor], ...
Reshard an FSDP-consolidated checkpoint and write outputs to files. The model weights are flattened before the resharding logic applies. The input checkpoint is expected to contain unflattened, FSDP-consolidated model weights. Args: :param input: A path to the input checkpoint (e.g. "opt-2.7b-dp1-mp2/reshard-model_part...
141,406
import logging import os import re from copy import deepcopy from glob import glob from typing import Any, Dict, List, Optional, Tuple import fire import torch import torch.nn.functional as F logger: logging.Logger = logging.getLogger("metaseq.scripts.reshard_fsdp") _STRING_TO_DTYPE: Dict[str, torch.dtype] = { "fp3...
Reshard FSDP checkpoints and write outputs to files. The model weights and optimizer states are merged from the sharded checkpoints before the resharding logic applies. The sharded checkpoints are expected to contain shard metadata. Args: :param input: A glob pattern specifying the path names of the input shards. (e.g....
141,407
import logging import os import re from glob import glob from typing import Any, Dict, List, Tuple import fire import torch logger: logging.Logger = logging.getLogger("metaseq.scripts.convert_metaseq_ft") def convert_weights( state_dict: Dict[str, Any], embedding_tokens: torch.Tensor, dtype: torch.dtype, ...
Convert Metaseq model weights into FasterTransformer format. The model parallel parts in the input are expected to contain unflattened, FSDP-consolidated model weights. The number of model parallel parts remains unchanged. Args: :param input: A glob pattern specifying the path names of the input shards. (e.g. "checkpoi...
141,408
import os from transformers import GPT2Tokenizer from metaseq import checkpoint_utils, tasks, utils import torch from metaseq.scripts.convert_to_singleton import create_generation_config_with_defaults from metaseq.distributed import utils as dist_utils from metaseq.distributed import fsdp_enable_wrap, fsdp_wrap from me...
null
141,409
import os from transformers import GPT2Tokenizer from metaseq import checkpoint_utils, tasks, utils import torch from metaseq.scripts.convert_to_singleton import create_generation_config_with_defaults from metaseq.distributed import utils as dist_utils from metaseq.distributed import fsdp_enable_wrap, fsdp_wrap from me...
null
141,410
import os from transformers import GPT2Tokenizer from metaseq import checkpoint_utils, tasks, utils import torch from metaseq.scripts.convert_to_singleton import create_generation_config_with_defaults from metaseq.distributed import utils as dist_utils from metaseq.distributed import fsdp_enable_wrap, fsdp_wrap from me...
null
141,411
import logging import os import re from glob import glob import fire import torch logger: logging.Logger = logging.getLogger("metaseq.scripts.reshard_mp") def _max_diff(tensor1: torch.Tensor, tensor2: torch.Tensor) -> float: assert tensor1.size() == tensor2.size() return (tensor1 - tensor2).abs().max().item() ...
Reshard model parallel (MP) parts and write outputs to files. The model weights are merged from the input parts before the resharding logic applies. The model parallel parts in the input are expected to contain unflattened, FSDP-consolidated model weights (see the script `reshard_fsdp.py` for related information.) Args...
141,412
import argparse import glob import logging import os import sys import torch from metaseq import options, tasks, checkpoint_utils, utils from metaseq.dataclass.configs import MetaseqConfig from metaseq.dataclass.utils import convert_namespace_to_omegaconf from metaseq.distributed import utils as distributed_utils from ...
Load up the model on all workers for Model Parallelism, then unflatten, move to cpu, and save to "restored.pt".
141,413
from typing import Any, Dict from metaseq.distributed import utils def shard_(optimizer, group): if not _has_fairscale: raise ImportError( "\n\nPlease install the fairscale package:" "\n\n pip install fairscale" ) class MetaseqOSS(OSS): @property def disable_mem_ef...
null
141,414
import types import torch class FusedAdamV1(torch.optim.Optimizer): """ Implements Adam algorithm. Currently GPU-only. Requires Apex to be installed via ``python setup.py install --cuda_ext --cpp_ext``. It has been proposed in `Adam: A Method for Stochastic Optimization`_. Compared to the original v...
Look for the FusedAdam optimizer from apex. We first try to load the "contrib" interface, which is a bit faster than the main interface, but is technically deprecated.
141,415
import logging import torch.nn as nn from torch.nn.parallel import DistributedDataParallel from metaseq.distributed import ( ModuleProxyWrapper, ) The provided code snippet includes necessary dependencies for implementing the `DistributedModel` function. Write a Python function `def DistributedModel(args, model, p...
Wrap a *model* to support distributed data parallel training. This is similar to the built-in DistributedDataParallel, but allows additional configuration of the DistributedDataParallel class to use, and also provides easier access to the wrapped model by forwarding requests for missing attributes to the wrapped model....
141,416
import logging import math from typing import Any, Dict, List, Optional import torch import torch.nn as nn from torch import Tensor from metaseq import utils from metaseq.dataclass.constants import UNSPECIFIED_DOC_SEP from metaseq.distributed import utils as distributed_utils, fsdp_wrap from metaseq.models import BaseD...
null
141,417
import logging from dataclasses import dataclass, field from typing import Optional import torch import torch.nn as nn from omegaconf import II from metaseq.dataclass import ChoiceEnum, MetaseqDataclass from metaseq.dataclass.constants import ATTN_CHOICES, UNSPECIFIED_DOC_SEP from metaseq.models import ( BaseModel,...
null