id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
21,600 | import json
import logging
import os
import sys
from contextlib import nullcontext
from dataclasses import dataclass, field
from typing import Optional
import datasets
import transformers
from datasets import load_dataset, load_metric
from transformers import (
AutoConfig,
AutoTokenizer,
DataCollatorWithPad... | null |
21,601 | import logging
import os
import random
import sys
from contextlib import nullcontext
from dataclasses import dataclass, field
from typing import Optional
import datasets
import numpy as np
import transformers
from datasets import load_dataset, load_metric
from sklearn.model_selection import StratifiedShuffleSplit
from ... | null |
21,602 | import logging
import os
import sys
from contextlib import nullcontext
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple, Union
import datasets
import numpy as np
import transformers
from datasets import ClassLabel, load_dataset, load_metric
from datasets.arrow_dataset import ... | null |
21,603 | import logging
import os
import sys
from contextlib import nullcontext
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple, Union
import datasets
import numpy as np
import transformers
from datasets import ClassLabel, load_dataset, load_metric
from datasets.arrow_dataset import ... | null |
21,604 | import logging
from pathlib import Path
from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, Union
import torch
from pydantic import Field
from sparseml.export.export_data import create_data_samples as create_data_samples_
from sparseml.export.helpers import apply_optimizations as apply_optimizatio... | A contract to create a model and optional dictionary of loaded_model_kwargs (any relevant objects created along with the model) :param source_path: The path to the model :param device: The device to use for the model :param task: The task to use for the model :param recipe: The recipe to use for the model :param export... |
21,605 | import logging
from pathlib import Path
from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, Union
import torch
from pydantic import Field
from sparseml.export.export_data import create_data_samples as create_data_samples_
from sparseml.export.helpers import apply_optimizations as apply_optimizatio... | A contract to create a dataloader and optional dictionary of loaded_dataloader_kwargs (any relevant objects created along with the dataloader) :param model: A model for which the data_loader is created :param task: The task to use for the model :param data_args: Arguments for instantiation of the dataset :param source_... |
21,606 | import logging
from pathlib import Path
from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, Union
import torch
from pydantic import Field
from sparseml.export.export_data import create_data_samples as create_data_samples_
from sparseml.export.helpers import apply_optimizations as apply_optimizatio... | null |
21,607 | import logging
from pathlib import Path
from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, Union
import torch
from pydantic import Field
from sparseml.export.export_data import create_data_samples as create_data_samples_
from sparseml.export.helpers import apply_optimizations as apply_optimizatio... | null |
21,608 | import logging
from pathlib import Path
from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, Union
import torch
from pydantic import Field
from sparseml.export.export_data import create_data_samples as create_data_samples_
from sparseml.export.helpers import apply_optimizations as apply_optimizatio... | null |
21,609 | import collections
import inspect
import logging
import math
import os
import warnings
from dataclasses import asdict
from typing import Any, Dict, List, Optional, Tuple, Union
import datasets
import torch
from torch import distributed as dist
from torch.nn import Module
from transformers import Trainer as HFTransforme... | null |
21,610 | import collections
import json
import logging
import os
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
from torch.nn import Module
from tqdm.auto import tqdm
from transformers import is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput
from sparseml.transformers.... | Post-processes the predictions of a question-answering model to convert them to answers that are substrings of the original contexts. This is the base postprocessing functions for models that only return start and end logits. :param examples: The non-preprocessed dataset. See main script for more :param features: The p... |
21,611 | import argparse
import collections
import copy
import inspect
import logging
import os
import shutil
from typing import Any, Dict, List, Optional, Union
from torch.nn import Module
from transformers import AutoConfig
from transformers.tokenization_utils_base import PaddingStrategy
import sparseml.core.session as sessio... | :param task: the task a dataset being loaded for :param tokenizer: the tokenizer to use for the dataset :param data_args: additional data args used to create a `DataTrainingArguments` instance for fetching the dataset |
21,612 | import argparse
import collections
import copy
import inspect
import logging
import os
import shutil
from typing import Any, Dict, List, Optional, Union
from torch.nn import Module
from transformers import AutoConfig
from transformers.tokenization_utils_base import PaddingStrategy
import sparseml.core.session as sessio... | null |
21,613 | import argparse
import collections
import copy
import inspect
import logging
import os
import shutil
from typing import Any, Dict, List, Optional, Union
from torch.nn import Module
from transformers import AutoConfig
from transformers.tokenization_utils_base import PaddingStrategy
import sparseml.core.session as sessio... | null |
21,614 | import argparse
import logging
import os
from pathlib import Path
from typing import Dict, Optional
from torch.nn import Module
from transformers import AutoConfig
import sparseml.core.session as session_manager
from sparseml.core.framework import Framework
from sparseml.pytorch.model_load.helpers import (
fallback... | Performs in place one shot sparsification/quantization of a model based on: :param model_path: path to Hugging Face stub :param dataset: Dataset to extract calibration data from :param dataset_config_name: Specific configuration to extract from calib dataset :param num_samples: Number of samples to extract from the dat... |
21,615 | from typing import List
import torch
from torch.nn import Module
from sparseml.modifiers.obcq.utils.helpers import (
cache_attention_inputs,
execute_offloaded_module,
)
def execute_offloaded_module(
module,
buffer,
dev,
nsamples=None,
overwrite_buffer=True,
cached_inputs=None,
**kwa... | Run a forward pass of OPT, used for perplexity evaluation :param model: Pytorch module to run :param data_loader: data to run through model :param device: device name to perform computation on :param nsamples: number of samples of data_loader to run, None to run them all :return: logits output of the model |
21,616 | from typing import List
import torch
from torch.nn import Module
from sparseml.modifiers.obcq.utils.helpers import (
cache_attention_inputs,
execute_offloaded_module,
)
def execute_offloaded_module(
module,
buffer,
dev,
nsamples=None,
overwrite_buffer=True,
cached_inputs=None,
**kwa... | Run a forward pass of Llama, used for perplexity evaluation :param model: Pytorch module to run :param data_loader: data to run through model :param device: device name to perform computation on :param nsamples: number of samples of data_loader to run, None to run them all :return: logits output of the model |
21,617 | import logging
import math
import os
import sys
from contextlib import nullcontext
from dataclasses import dataclass, field
from itertools import chain
from typing import Any, Callable, Optional
import datasets
import transformers
from datasets import concatenate_datasets, load_dataset, load_metric
from transformers im... | null |
21,618 | import inspect
import logging
import os
from pathlib import Path
from typing import Any, Dict, Optional, Tuple, Union
import torch
from torch.nn import Module
from transformers import (
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForQuestionAnswering,
AutoModelForSequenceClassification,
Aut... | Get a tokenizer source used for both student and teacher, assuming that they could be shared :param student: the student model :param teacher: the teacher model :return: the source for the tokenizer shared between teacher and model |
21,619 | from typing import Dict
from sparsezoo.utils.registry import RegistryMixin
def custom_evolved_codealpaca_dataset(data: Dict):
PROMPT_DICT = """[Instruction]:\n{instruction}\n\n[Response]:"""
data["prompt"] = PROMPT_DICT.format_map(data)
data["text"] = data["prompt"] + data["output"]
return data | null |
21,620 | import inspect
import logging
import os
from collections import OrderedDict
from contextlib import suppress
from enum import Enum
from pathlib import Path
from typing import Iterable, List, Optional
from typing import OrderedDict as OrderedDictType
from typing import Tuple, Union
import requests
import torch
import tra... | Takes the `training_outputs_dir` (the directory where the pipeline saves its training artifacts), and saves the training artifacts to `output_dir` as a sparsezoo Model class object. :param output_dir: The output path where the artifacts are saved (adhering to the structure of sparsezoo Model class object) :param traini... |
21,621 | import inspect
import logging
import os
from collections import OrderedDict
from contextlib import suppress
from enum import Enum
from pathlib import Path
from typing import Iterable, List, Optional
from typing import OrderedDict as OrderedDictType
from typing import Tuple, Union
import requests
import torch
import tra... | Resolve the recipe to apply to the model. :param recipe: the recipe to apply to the model. It can be one of the following: - None This means that we are not either not applying any recipe and allowing the model to potentially infer the appropriate pre-existing recipe from the model_path - a path to the recipe file This... |
21,622 | import inspect
import logging
import os
from collections import OrderedDict
from contextlib import suppress
from enum import Enum
from pathlib import Path
from typing import Iterable, List, Optional
from typing import OrderedDict as OrderedDictType
from typing import Tuple, Union
import requests
import torch
import tra... | Fetches the recipe path for the given target. This method will also download the recipe if it is not already downloaded. Takes care of three scenarios: 1. target is a local path to a model directory (looks for recipe.yaml in the directory) 2. target is a SparseZoo stub (downloads and returns the path to the default rec... |
21,623 | import logging
from typing import Any, Dict, Optional, Union
import datasets
from torch.nn import Module
from transformers import AutoConfig
from sparseml.transformers.utils.helpers import TaskNames
def load_dataset(*args, **kwargs):
# a wrapper around datasets.load_dataset
# to be expanded in the future
r... | null |
21,624 | from typing import Dict, Optional
import numpy
from sklearn.metrics import precision_recall_fscore_support
The provided code snippet includes necessary dependencies for implementing the `multi_label_precision_recall_f1` function. Write a Python function `def multi_label_precision_recall_f1( predictions: numpy.ndar... | computes per class and macro-averaged precision, recall, and f1 for multiple model sample predictions where targets may contain multiple labels :param predictions: array of model predictions, shape (num_samples, num_labels) where positive predictions are 1 and negative predictions are 0 :param targets: array of sample ... |
21,625 | import difflib
import re
from typing import Dict, List, Optional, Tuple, Union
import torch
from packaging import version
from torch.nn import Linear, Module, Parameter
from torch.nn.modules.conv import _ConvNd
from sparseml.core.model.base import ModelParameterizedLayer
from sparseml.utils.fsdp.context import fix_fsdp... | null |
21,626 | import difflib
import re
from typing import Dict, List, Optional, Tuple, Union
import torch
from packaging import version
from torch.nn import Linear, Module, Parameter
from torch.nn.modules.conv import _ConvNd
from sparseml.core.model.base import ModelParameterizedLayer
from sparseml.utils.fsdp.context import fix_fsdp... | null |
21,627 | import difflib
import re
from typing import Dict, List, Optional, Tuple, Union
import torch
from packaging import version
from torch.nn import Linear, Module, Parameter
from torch.nn.modules.conv import _ConvNd
from sparseml.core.model.base import ModelParameterizedLayer
from sparseml.utils.fsdp.context import fix_fsdp... | null |
21,628 | import difflib
import re
from typing import Dict, List, Optional, Tuple, Union
import torch
from packaging import version
from torch.nn import Linear, Module, Parameter
from torch.nn.modules.conv import _ConvNd
from sparseml.core.model.base import ModelParameterizedLayer
from sparseml.utils.fsdp.context import fix_fsdp... | Determines if any layers in the model have quantization enabled by checking for weight_fake_quant attributes :param module: PyTorch model to check for quantization :return: True if quantization is active anywhere in the model, False otherwise |
21,629 | import difflib
import re
from typing import Dict, List, Optional, Tuple, Union
import torch
from packaging import version
from torch.nn import Linear, Module, Parameter
from torch.nn.modules.conv import _ConvNd
from sparseml.core.model.base import ModelParameterizedLayer
from sparseml.utils.fsdp.context import fix_fsdp... | null |
21,630 | import difflib
import re
from typing import Dict, List, Optional, Tuple, Union
import torch
from packaging import version
from torch.nn import Linear, Module, Parameter
from torch.nn.modules.conv import _ConvNd
from sparseml.core.model.base import ModelParameterizedLayer
from sparseml.utils.fsdp.context import fix_fsdp... | Given a target regex, find the layer name in the module that most closely matches the name_to_match string. This is used to matches submodules in the same layer, for instance matching "re.*k_proj" to "model.decoder.layer.0.q_proj" to find the k_proj that exists in layer 0. :param target: regex to search for :param name... |
21,631 | import difflib
import re
from typing import Dict, List, Optional, Tuple, Union
import torch
from packaging import version
from torch.nn import Linear, Module, Parameter
from torch.nn.modules.conv import _ConvNd
from sparseml.core.model.base import ModelParameterizedLayer
from sparseml.utils.fsdp.context import fix_fsdp... | Get list of module classes that shouldn't be split when sharding. For Hugging Face Transformer models, this is the decoder layer type. For other types of models, this just returns all module names. :return: list of class names that shouldn't be split |
21,632 | import logging
import operator
from pathlib import Path
from typing import Optional, Union
import torch
from torch.nn import Module
from sparseml.core.model import ModifiableModel
from sparseml.pytorch.model_load.helpers import save_model_and_recipe
from sparseml.utils.pytorch import set_layer
def is_fsdp_model(model: ... | Given a model that may or may not have a distributed wrapper, set the underlying wrapped model. :param input_model: input model to be updated :param updated_wrapped: model to inject into input_model |
21,633 | import logging
import operator
from pathlib import Path
from typing import Optional, Union
import torch
from torch.nn import Module
from sparseml.core.model import ModifiableModel
from sparseml.pytorch.model_load.helpers import save_model_and_recipe
from sparseml.utils.pytorch import set_layer
def save_model_and_recip... | Recursively unwraps an FSDP model, then saves the unwrapped model and the currently active recipe to disk :param model: model to unwrap :param accelerator: Accelerator instance used to perform unwrapping :param output_dir: where to save output model :param tokenizer: tokenizer used by the model |
21,634 | import logging
import operator
from pathlib import Path
from typing import Optional, Union
try:
from torch.distributed.fsdp import (
FullStateDictConfig,
FullyShardedDataParallel,
StateDictType,
)
except ImportError:
FullyShardedDataParallel = None
import torch
from torch.nn import M... | Looks for state dicts in the output directory and overwrites them with cpu state dicts. this is needed for quantized models trained with FSDP as the state dict contains device information, which can cause issues when loading the model using transformers AutoModel.from_pretrained(...) if the device information is not re... |
21,635 | import logging
import operator
from pathlib import Path
from typing import Optional, Union
import torch
from torch.nn import Module
from sparseml.core.model import ModifiableModel
from sparseml.pytorch.model_load.helpers import save_model_and_recipe
from sparseml.utils.pytorch import set_layer
The provided code snippe... | Gathers the full FSDP state dict of the model onto rank0 GPU, then uses it to save the pretrained FSDP model to disk :param model: model to save :param accelerator: Accelerator instance used to perform unwrapping :param output_dir: where to save output model :param save_safetensors: True to safe in safetensors format, ... |
21,636 | import logging
import operator
from pathlib import Path
from typing import Optional, Union
import torch
from torch.nn import Module
from sparseml.core.model import ModifiableModel
from sparseml.pytorch.model_load.helpers import save_model_and_recipe
from sparseml.utils.pytorch import set_layer
def is_fsdp_model(model: ... | Gets the closest parent of layer_name that is wrapped by FSDP. If no FSDP wrapper is found just return None :param layer_name: layer name in model to get parent of :model: pytorch module to search through :return: FSDP wrapped parent of layer_name if available, otherwise None |
21,637 | from contextlib import nullcontext
The provided code snippet includes necessary dependencies for implementing the `main_process_first_context` function. Write a Python function `def main_process_first_context()` to solve the following problem:
Creates a context manager where the main process runs the block before all ... | Creates a context manager where the main process runs the block before all other processes. Returns a nullcontext when called from a single process application. |
21,638 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | :param val: the value to validate, check that it is a list (and flattens it), otherwise checks that it's an __ALL__ or __ALL_PRUNABLE__ string, otherwise raises a ValueError :param error_desc: the description to raise an error with in the event that the val wasn't valid :return: the validated version of the param |
21,639 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | Bucket iterable into subarray consisting of the first top percentage followed by the rest of the iterable sliced into equal sliced groups. :param val: The iterable to bucket :param num_buckets: The number of buckets to group the iterable into, does not include the top bucket :param edge_percent: Group the first percent... |
21,640 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | note, caps values at their min of x0 and max x1, designed to not work outside of that range for implementation reasons :param x_cur: the current value for x, should be between x0 and x1 :param x0: the minimum for x to interpolate between :param x1: the maximum for x to interpolate between :param y0: the minimum for y t... |
21,641 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | interpolate for input values within a list of measurements linearly :param measurements: the measurements to interpolate the output value between :param x_val: the target values to interpolate to the second dimension :return: a list of tuples containing the target values, interpolated values |
21,642 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | Calculate the interpolated integal for a group of measurements of the form [(x0, y0), (x1, y1), ...] :param measurements: the measurements to calculate the integral for :return: the integral or area under the curve for the measurements given |
21,643 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | :param path: the file path to create a unique version of (append numbers until one doesn't exist) :param check_number: the number to begin checking for unique versions at :return: the unique directory path |
21,644 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | Return the number of files that match the given pattern under the given path :param path: the path to the directory to look for files under :param pattern: the pattern the files must match to be counted :return: the number of files matching the pattern under the directory |
21,645 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | Return the total size, in bytes, for a path on the file system :param path: the path (directory or file) to get the size for :return: the size of the path, in bytes, as stored on disk |
21,646 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | :param val: value to check if it is a url or not :return: True if value is a URL, False otherwise |
21,647 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | Save a numpy array or collection of numpy arrays to disk :param array: the array or collection of arrays to save :param export_dir: the directory to export the numpy file into :param name: the name of the file to export to (without extension) :param npz: True to save as an npz compressed file, False for standard npy. N... |
21,648 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | Load labels and data from disk or from memory and group them together. Assumes sorted ordering for on disk. Will match between when a file glob is passed for either data and/or labels. :param data: the file glob, file path to numpy data tar ball, or list of arrays to use for data :param labels: the file glob, file path... |
21,649 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | :param tensors: the tensors to export to a saved numpy array file :param export_dir: the directory to export the files in :param name_prefix: the prefix name for the tensors to save as, will append info about the position of the tensor in a list or dict in addition to the .npy file format :param counter: the current co... |
21,650 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | :param optim_full_name: A name of a pretrained model optimization. i.e. 'pruned-moderate-deepsparse', 'pruned-aggressive', 'base' :return: A tuple representing the corresponding SparseZoo model sparse_name, sparse_category, and sparse_target values with appropriate defaults when not present. |
21,651 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | Converts a json list file to jsonl file format (used for sharding efficienty) e.x. [{"a": 1}, {"a": 1}] would convert to: {"a": 1} {"a": 1} :param json_file_path: file path to a json file path containing a json list of objects :param overwrite: If True, the existing json file will be overwritten, if False, the file wil... |
21,652 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | Convert a tuple of kwargs to a dict of kwargs. This function is used to enable the click parsing of kwargs. Example use: ``` @click.command( context_settings=dict( ignore_unknown_options=True) ) @click.argument(...) @click.option(...) ... @click.argument("kwargs", nargs=-1, type=click.UNPROCESSED) def main(..., kwargs)... |
21,653 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | Helper function to download the training directory from a zoo stub, takes care of downloading the missing files in the training directory if any (This can happen if a some subset of files in the training directory were downloaded before) :param zoo_stub: The zoo stub to download the training directory from :return: The... |
21,654 | import ast
import errno
import fnmatch
import importlib.metadata
import importlib.util
import json
import logging
import os
import sys
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
from urllib.parse import urlparse
impor... | A helper function to check if a package is available and optionally return its version. This function enforces a check that the package is available and is not just a directory/file with the same name as the package. inspired from: https://github.com/huggingface/transformers/blob/965cf677695dd363285831afca8cf479cf0c600... |
21,655 | from typing import Callable, List
def _doc_merge(wrapped: Callable, wrapper: Callable):
stripped_wrapped = _strip_doc_indent(wrapped.__doc__)
stripped_wrapper = _strip_doc_indent(wrapper.__doc__)
merge = []
# check for return at end of doc string in wrapped
if len(stripped_wrapped) > 0 and ":return"... | A wrapper decorator to be applied as a decorator to a function. Merges the decorated function properties with wrapped. :param wrapped: the wrapped function to merge decorations with :return: the decorator to apply to the function |
21,656 | import os
The provided code snippet includes necessary dependencies for implementing the `default_dataset_path` function. Write a Python function `def default_dataset_path(name: str) -> str` to solve the following problem:
:param name: name of the dataset to get a path for :return: the default path to save the dataset... | :param name: name of the dataset to get a path for :return: the default path to save the dataset at |
21,657 | import math
import os
from datetime import datetime
import numpy as np
import tensorflow as tf
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from sparseml.keras.optim import ScheduledModifierManage... | Download pretrained model and a pruning recipe |
21,658 | import math
import os
from datetime import datetime
import numpy as np
import tensorflow as tf
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from sparseml.keras.optim import ScheduledModifierManage... | Load and normalize the Cifar-10 dataset |
21,659 | import math
import os
from datetime import datetime
import numpy as np
import tensorflow as tf
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from sparseml.keras.optim import ScheduledModifierManage... | Create model checkpoint callback |
21,660 | import argparse
import inspect
import json
import math
import os
from typing import Optional, Tuple
import numpy
import tensorflow
from sparseml import get_main_logger
from sparseml.keras.datasets import Dataset, DatasetRegistry
from sparseml.keras.models import ModelRegistry
from sparseml.keras.optim import ScheduledM... | null |
21,661 | import argparse
import inspect
import json
import math
import os
from typing import Optional, Tuple
import numpy
import tensorflow
from sparseml import get_main_logger
from sparseml.keras.datasets import Dataset, DatasetRegistry
from sparseml.keras.models import ModelRegistry
from sparseml.keras.optim import ScheduledM... | null |
21,662 | import argparse
import inspect
import json
import math
import os
from typing import Optional, Tuple
import numpy
import tensorflow
from sparseml import get_main_logger
from sparseml.keras.datasets import Dataset, DatasetRegistry
from sparseml.keras.models import ModelRegistry
from sparseml.keras.optim import ScheduledM... | null |
21,663 | import argparse
import inspect
import json
import math
import os
from typing import Optional, Tuple
import numpy
import tensorflow
from sparseml import get_main_logger
from sparseml.keras.datasets import Dataset, DatasetRegistry
from sparseml.keras.models import ModelRegistry
from sparseml.keras.optim import ScheduledM... | null |
21,664 | import json
from dataclasses import dataclass, field
from typing import Any, Optional, Tuple
from torch.nn import Module
from torch.utils.data import DataLoader
from tqdm import tqdm
import utils
from argparser_.nm_argparser_ import NmArgumentParser
from sparseml import get_main_logger
from sparseml.pytorch.models impo... | Utility method to export the model and data :param args : An ExportArgs object containing config for export task. :param model: loaded model architecture to export :param val_loader: A DataLoader for validation data :param save_dir: Directory to store checkpoints at during exporting process |
21,665 | import json
from dataclasses import dataclass, field
from typing import Any, Optional, Tuple
from torch.nn import Module
from torch.utils.data import DataLoader
from tqdm import tqdm
import utils
from argparser_.nm_argparser_ import NmArgumentParser
from sparseml import get_main_logger
from sparseml.pytorch.models impo... | Pre-export setup :param args_ : An ExportArgs object containing config for export task. |
21,666 | import argparse
import json
import os
from dataclasses import dataclass, field
from typing import Any, List, Optional, Tuple
import torch
from torch.nn import Module
from torch.utils.data import DataLoader
import utils
from argparser_.nm_argparser_ import NmArgumentParser
from sparseml import get_main_logger
from spars... | Utility function to drive the training processing :param train_args: A TrainingArguments object with arguments for current training task :param model: model architecture to train :param train_loader: A DataLoader for training data :param val_loader: A DataLoader for validation data :param input_shape: A tuple of intege... |
21,667 | import os
from enum import Enum, auto, unique
from typing import Any, List, Optional, Tuple, Union
import torch
from torch.nn import Module
from torch.nn import functional as torch_functional
from torch.optim import Optimizer
from torch.utils.data import DataLoader
from sparseml.pytorch.datasets import DatasetRegistry,... | null |
21,668 | import os
from enum import Enum, auto, unique
from typing import Any, List, Optional, Tuple, Union
import torch
from torch.nn import Module
from torch.nn import functional as torch_functional
from torch.optim import Optimizer
from torch.utils.data import DataLoader
from sparseml.pytorch.datasets import DatasetRegistry,... | :param args: Object containing relevant configuration for the task :param image_size: A Tuple of integers representing the shape of input image :param task: The current task being performed :return: 4 element tuple with the following format (train_dataset, train_loader, val_dataset, val_loader) |
21,669 | import os
from enum import Enum, auto, unique
from typing import Any, List, Optional, Tuple, Union
import torch
from torch.nn import Module
from torch.nn import functional as torch_functional
from torch.optim import Optimizer
from torch.utils.data import DataLoader
from sparseml.pytorch.datasets import DatasetRegistry,... | :param args: object with configuration for model classes :param num_classes: Integer representing the number of output classes :returns: A Module object representing the created model |
21,670 | import os
from enum import Enum, auto, unique
from typing import Any, List, Optional, Tuple, Union
import torch
from torch.nn import Module
from torch.nn import functional as torch_functional
from torch.optim import Optimizer
from torch.utils.data import DataLoader
from sparseml.pytorch.datasets import DatasetRegistry,... | :param args: Object with configuration settings :param train_dataset: dataset representing training data :param val_dataset: dataset representing validation data :return: An integer representing the number of classes |
21,671 | import os
from enum import Enum, auto, unique
from typing import Any, List, Optional, Tuple, Union
import torch
from torch.nn import Module
from torch.nn import functional as torch_functional
from torch.optim import Optimizer
from torch.utils.data import DataLoader
from sparseml.pytorch.datasets import DatasetRegistry,... | :param arch_key: The model architecture :param training: True if training task started else False :param task: current task being executed |
21,672 | import os
from enum import Enum, auto, unique
from typing import Any, List, Optional, Tuple, Union
import torch
from torch.nn import Module
from torch.nn import functional as torch_functional
from torch.optim import Optimizer
from torch.utils.data import DataLoader
from sparseml.pytorch.datasets import DatasetRegistry,... | :param train_args : An object with task specific config :param model: model architecture to train :param train_loader: A DataLoader for training data :param loggers: List of loggers to use during training process :type train_args: TrainingArguments |
21,673 | import os
from enum import Enum, auto, unique
from typing import Any, List, Optional, Tuple, Union
import torch
from torch.nn import Module
from torch.nn import functional as torch_functional
from torch.optim import Optimizer
from torch.utils.data import DataLoader
from sparseml.pytorch.datasets import DatasetRegistry,... | :param recipe_manager: The ScheduleModified manager to save recipes :param save_dir: The directory to save the recipe |
21,674 | import os
from enum import Enum, auto, unique
from typing import Any, List, Optional, Tuple, Union
import torch
from torch.nn import Module
from torch.nn import functional as torch_functional
from torch.optim import Optimizer
from torch.utils.data import DataLoader
from sparseml.pytorch.datasets import DatasetRegistry,... | :param model: model architecture :param optim: The optimizer used :param input_shape: A tuple of integers representing the input shape :param save_name: name to save model to :param save_dir: directory to save results in :param epoch: integer representing umber of epochs to :param val_res: results from validation run :... |
21,675 | import json
import os
from dataclasses import dataclass, field
from typing import Any, List, Optional
from torch.utils.data import DataLoader
import utils
from argparser_.nm_argparser_ import NmArgumentParser
from sparseml import get_main_logger
from sparseml.pytorch.models import ModelRegistry
from sparseml.pytorch.op... | Utility function for pruning sensitivity analysis :param args : A PRAnalysisArguments object containing config for current analysis :param model: loaded model architecture to analyse :param train_loader: A DataLoader for training data :param save_dir: Directory to save results :param loggers: List of loggers to use dur... |
21,676 | import json
import os
from dataclasses import dataclass, field
from torch.nn import Module
from torch.optim import SGD
from torch.utils.data import DataLoader
import utils
from argparser_.nm_argparser_ import NmArgumentParser
from sparseml import get_main_logger
from sparseml.pytorch.models import ModelRegistry
from sp... | Utility function to run learning rate sensitivity analysis :param args: An LRAnalysisArguments object containing config for current LR analysis task. :param model: loaded model architecture to analyse :param train_loader: A DataLoader for training data :param save_dir: Directory to save results |
21,677 | import dataclasses
import json
import re
import sys
from argparse import ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from pathlib import Path
from typing import Any, Iterable, List, NewType, Optional, Tuple, Union
def string_to_bool(v):
if isinstance(v, bool):
return v
... | null |
21,678 | import argparse
import os
import time
from types import ModuleType
import torch
from torch.nn import CrossEntropyLoss
from torch.optim import SGD
from torch.utils.data import DataLoader
from torchvision import models
from sparseml.pytorch.datasets.classification import ImageFolderDataset
from sparseml.pytorch.optim imp... | null |
21,679 | import argparse
import os
import time
from types import ModuleType
import torch
from torch.nn import CrossEntropyLoss
from torch.optim import SGD
from torch.utils.data import DataLoader
from torchvision import models
from sparseml.pytorch.datasets.classification import ImageFolderDataset
from sparseml.pytorch.optim imp... | null |
21,680 | import argparse
import os
import time
from types import ModuleType
import torch
from torch.nn import CrossEntropyLoss
from torch.optim import SGD
from torch.utils.data import DataLoader
from torchvision import models
from sparseml.pytorch.datasets.classification import ImageFolderDataset
from sparseml.pytorch.optim imp... | null |
21,681 | import argparse
import os
import time
from types import ModuleType
import torch
from torch.nn import CrossEntropyLoss
from torch.optim import SGD
from torch.utils.data import DataLoader
from torchvision import models
from sparseml.pytorch.datasets.classification import ImageFolderDataset
from sparseml.pytorch.optim imp... | null |
21,682 | import argparse
import os
import time
from types import ModuleType
import torch
from torch.nn import CrossEntropyLoss
from torch.optim import SGD
from torch.utils.data import DataLoader
from torchvision import models
from sparseml.pytorch.datasets.classification import ImageFolderDataset
from sparseml.pytorch.optim imp... | null |
21,683 | import argparse
import json
import math
import os
from typing import Dict, Optional, Tuple
import numpy
from sparseml import get_main_logger
from sparseml.tensorflow_v1.datasets import (
Dataset,
DatasetRegistry,
create_split_iterators_handle,
)
from sparseml.tensorflow_v1.models import ModelRegistry
from s... | null |
21,684 | import argparse
import json
import math
import os
from typing import Dict, Optional, Tuple
import numpy
from sparseml import get_main_logger
from sparseml.tensorflow_v1.datasets import (
Dataset,
DatasetRegistry,
create_split_iterators_handle,
)
from sparseml.tensorflow_v1.models import ModelRegistry
from s... | null |
21,685 | import argparse
import json
import math
import os
from typing import Dict, Optional, Tuple
import numpy
from sparseml import get_main_logger
from sparseml.tensorflow_v1.datasets import (
Dataset,
DatasetRegistry,
create_split_iterators_handle,
)
from sparseml.tensorflow_v1.models import ModelRegistry
from s... | null |
21,686 | import argparse
from collections import OrderedDict
from pathlib import Path
from typing import Any, Union
import torch
import open_clip
from clip_models import TextModel
from sparseml.pytorch.utils import export_onnx
def _export_onnx(
module: torch.nn.Module,
sample_batch: Any,
file_path: Union[Path, str],... | null |
21,687 | import argparse
from collections import OrderedDict
from pathlib import Path
from typing import Any, Union
import torch
import open_clip
from clip_models import TextModel
from sparseml.pytorch.utils import export_onnx
def _export_onnx(
module: torch.nn.Module,
sample_batch: Any,
file_path: Union[Path, str],... | null |
21,688 | import argparse
from collections import OrderedDict
from pathlib import Path
from typing import Any, Union
import torch
import open_clip
from clip_models import TextModel
from sparseml.pytorch.utils import export_onnx
def _export_onnx(
module: torch.nn.Module,
sample_batch: Any,
file_path: Union[Path, str],... | null |
21,689 | import math
import torch
import torch.nn.functional as F
from sparseml.pytorch.optim.manager import ScheduledModifierManager
from sparseml.pytorch.optim.optimizer import ScheduledOptimizer
from sparseml.pytorch.utils import ModuleExporter, logger
from trainer_qa import QuestionAnsweringTrainer
The provided code snippe... | Export a trained model to ONNX :param model: trained model :param dataloader: dataloader to get sample batch :param output_dir: output directory for ONNX model |
21,691 | import argparse
import os
import json
import transformers
from filelock import FileLock
from transformers import (
AutoConfig,
AutoModelForSeq2SeqLM,
AutoTokenizer,
DataCollatorForSeq2Seq,
HfArgumentParser,
Seq2SeqTrainer,
Seq2SeqTrainingArguments,
set_seed,
)
def load_qid2query(filenam... | null |
21,692 | import re
import sys
import statistics
from collections import Counter
def load_reference(path_to_reference):
"""Load Reference reference relevant passages
Args:path_to_reference (str): path to a file to load.
Returns:qids_to_relevant_passageids (dict): dictionary mapping from query_id (int) to relevant pas... | Compute MRR metric Args: p_path_to_reference_file (str): path to reference file. Reference file should contain lines in the following format: QUERYID\tPASSAGEID Where PASSAGEID is a relevant passage for a query. Note QUERYID can repeat on different lines with different PASSAGEIDs p_path_to_candidate_file (str): path to... |
21,693 | import argparse
import os
import json
def load_qid2query(filename):
qid2query = {}
with open(filename, 'r') as f:
for l in f:
l = l.strip().split('\t')
qid2query[int(l[0])] = l[1]
return qid2query | null |
21,694 | import argparse
import os
import json
def load_qrels(filename, collection, qid2query):
qrels = {}
with open(filename, 'r') as f:
for l in f:
l = l.strip().split('\t')
qrels[qid2query[int(l[0])]] = collection[int(l[2])]
return qrels | null |
21,695 | import os
import json
import argparse
def convert_collection(args):
with open(args.output_path, 'w', encoding='utf-8') as w:
with open(args.collection_path, encoding='utf-8') as f:
for i, line in enumerate(f):
id, body = line.split('\t')
output_dict = {'id': id, ... | null |
21,696 | import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional
import random
import math
import nltk
import wandb
import numpy as np
from datasets import load_dataset, load_metric
import transformers
from filelock import FileLock
from transformers import (
AutoConfig,
A... | null |
21,697 | import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional
import random
import math
import nltk
import wandb
import numpy as np
from datasets import load_dataset, load_metric
import transformers
from filelock import FileLock
from transformers import (
AutoConfig,
A... | null |
21,698 | import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional
import random
import math
import nltk
import wandb
import numpy as np
from datasets import load_dataset, load_metric
import transformers
from filelock import FileLock
from transformers import (
AutoConfig,
A... | null |
21,699 | import logging
import math
import os
import random
import sys
import time
from typing import Tuple
import hydra
import torch
from omegaconf import DictConfig, OmegaConf
from torch import Tensor as T
from torch import nn
from dpr.models import init_biencoder_components
from dpr.models.biencoder import BiEncoder, BiEncod... | null |
21,700 | import collections
import glob
import json
import logging
import math
import multiprocessing
import os
import pickle
import torch
from functools import partial
from typing import Tuple, List, Dict, Iterable, Optional
from torch import Tensor as T
from tqdm import tqdm
from dpr.utils.data_utils import Tensorizer, read_s... | Converts the file with dense retriever(or any compatible file format) results into the reader input data and serializes them into a set of files. Conversion splits the input data into multiple chunks and processes them in parallel. Each chunk results are stored in a separate file with name out_file_prefix.{number}.pkl ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.