id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
22,119
import sys import re import numpy as np import cv2 import torch from PIL import Image from .pallete import get_mask_pallete The provided code snippet includes necessary dependencies for implementing the `resize_depth` function. Write a Python function `def resize_depth(depth, width, height)` to solve the following pro...
Resize depth map and bring to CPU (numpy). Args: depth (tensor): depth width (int): image width height (int): image height Returns: array: processed depth
22,120
import os import glob import cv2 import argparse import torch import torch.nn.functional as F import util.io from torchvision.transforms import Compose from dpt.models import DPTSegmentationModel from dpt.transforms import Resize, NormalizeImage, PrepareForNet class DPTSegmentationModel(DPT): def __init__(self, nu...
Run segmentation network Args: input_path (str): path to input folder output_path (str): path to output folder model_path (str): path to saved model
22,121
import torch import os import json import copy import numpy as np from PIL import Image from random import randint from tqdm import tqdm from diff_gaussian_rasterization import GaussianRasterizer as Renderer from helpers import setup_camera, l1_loss_v1, l1_loss_v2, weighted_l2_loss_v1, weighted_l2_loss_v2, quat_mult, \...
null
22,122
import torch import numpy as np import open3d as o3d import time from diff_gaussian_rasterization import GaussianRasterizer as Renderer from helpers import setup_camera, quat_mult from external import build_rotation from colormap import colormap from copy import deepcopy RENDER_MODE = 'color' ADDITIONAL_LINES = None ...
null
22,123
import torch import torch.nn.functional as func from torch.autograd import Variable from math import exp def calc_mse(img1, img2): return ((img1 - img2) ** 2).view(img1.shape[0], -1).mean(1, keepdim=True)
null
22,124
import torch import math from typing import Type, Dict, Any, Tuple, Callable from . import merge from .utils import isinstance_str, init_generator def make_tome_block(block_class: Type[torch.nn.Module]) -> Type[torch.nn.Module]: """ Make a patched class on the fly so we don't have to import any specific modules...
Patches a stable diffusion model with ToMe. Apply this to the highest level stable diffusion object (i.e., it should have a .model.diffusion_model). Important Args: - model: A top level Stable Diffusion module to patch in place. Should have a ".model.diffusion_model" - ratio: The ratio of tokens to merge. I.e., 0.4 wou...
22,125
import itertools import time from typing import Optional from tml.common.batch import DataclassBatch from tml.ml_logging.torch_logging import logging import pyarrow as pa import torch The provided code snippet includes necessary dependencies for implementing the `roundrobin` function. Write a Python function `def roun...
Round robin through provided iterables, useful for simple load balancing. Adapted from https://docs.python.org/3/library/itertools.html.
22,126
import itertools import time from typing import Optional from tml.common.batch import DataclassBatch from tml.ml_logging.torch_logging import logging import pyarrow as pa import torch def speed_check(data_loader, max_steps: int, frequency: int, peek: Optional[int]): num_examples = 0 prev = time.perf_counter() fo...
null
22,127
import itertools import time from typing import Optional from tml.common.batch import DataclassBatch from tml.ml_logging.torch_logging import logging import pyarrow as pa import torch def pa_to_torch(array: pa.array) -> torch.Tensor: return torch.from_numpy(array.to_numpy()) def create_default_pa_to_batch(schema) ->...
null
22,128
from typing import Optional import uuid from tml.ml_logging.torch_logging import logging import tml.machines.environment as env import packaging.version import tensorflow as tf from tensorflow.python.data.experimental.ops.data_service_ops import ( _from_dataset_id, _register_dataset, ) import torch.distributed as d...
null
22,129
from typing import Optional import uuid from tml.ml_logging.torch_logging import logging import tml.machines.environment as env import packaging.version import tensorflow as tf from tensorflow.python.data.experimental.ops.data_service_ops import ( _from_dataset_id, _register_dataset, ) import torch.distributed as d...
Torch-compatible and distributed-training-aware dataset service distributor. - rank 0 process will register the given dataset. - rank 0 process will broadcast job name and dataset id. - all rank processes will consume from the same job/dataset. Without this, dataset workers will try to serve 1 job per rank process and ...
22,130
import abc import functools import random from typing import Optional from fsspec.implementations.local import LocalFileSystem import pyarrow.dataset as pads import pyarrow as pa import pyarrow.parquet import pyarrow.flight from pyarrow.ipc import IpcWriteOptions import torch from tml.common.batch import DataclassBatch...
null
22,131
from typing import Tuple, Union import torch import torchmetrics def update_mean( current_mean: torch.Tensor, current_weight_sum: torch.Tensor, value: torch.Tensor, weight: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor]: """ Update the mean according to Welford formula: https://en.wikipedia.org/wiki...
Merge the state from multiple workers. Args: state: A tensor with the first dimension indicating workers. Returns: The accumulated mean from all workers.
22,132
from typing import Union from tml.ml_logging.torch_logging import logging import torch import torchmetrics from torchmetrics.utilities.data import dim_zero_cat The provided code snippet includes necessary dependencies for implementing the `_compute_helper` function. Write a Python function `def _compute_helper( pred...
Compute AUROC. Args: predictions: The predictions probabilities. target: The target. weights: The sample weights to assign to each sample in the batch. max_positive_negative_weighted_sum: The sum of the weights for the positive labels. min_positive_negative_weighted_sum: equal_predictions_as_incorrect: For positive & n...
22,133
import copy from functools import partial from typing import Union from tml.metrics import aggregation import torch import torchmetrics The provided code snippet includes necessary dependencies for implementing the `_smooth` function. Write a Python function `def _smooth( value: torch.Tensor, label_smoothing: Union[...
Smooth given values. Args: value: Value to smooth. label_smoothing: smoothing constant. Returns: Smoothed values.
22,134
import copy from functools import partial from typing import Union from tml.metrics import aggregation import torch import torchmetrics The provided code snippet includes necessary dependencies for implementing the `_binary_cross_entropy_with_clipping` function. Write a Python function `def _binary_cross_entropy_with_...
Clip Predictions and apply binary cross entropy. This is done to match the implementation in keras at https://github.com/keras-team/keras/blob/r2.9/keras/backend.py#L5294-L5300 Args: predictions: Predicted probabilities. target: Ground truth. epsilon: Epsilon fuzz factor used to clip the predictions. reduction: The red...
22,135
import typing import tml.core.config as base_config import pydantic class OptimizerConfig(base_config.BaseConfig): learning_rate: LearningRate = pydantic.Field( None, description="Constant learning rates", ) adam: AdamConfig = pydantic.Field(None, one_of="optimizer") sgd: SgdConfig = pydantic.Field(None...
null
22,136
from typing import Dict, Tuple import math import bisect from tml.optimizers.config import ( LearningRate, OptimizerConfig, ) import torch from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler from tml.ml_logging.torch_logging import logging The provided code snippet includes necessar...
Compute a learning rate.
22,137
from typing import Dict, Tuple import math import bisect from tml.optimizers.config import ( LearningRate, OptimizerConfig, ) import torch from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler from tml.ml_logging.torch_logging import logging class LRShim(_LRScheduler): """Shim to get...
Builds an optimizer and LR scheduler from an OptimizerConfig. Note: use this when you want the same optimizer and learning rate schedule for all your parameters.
22,138
from typing import Iterable, Optional, Dict, Callable, List import torch from torch.optim.lr_scheduler import _LRScheduler import torchmetrics as tm from tml.ml_logging.torch_logging import logging def train( model: torch.nn.Module, optimizer: torch.optim.Optimizer, train_steps: int, dataset: Iterable, sched...
null
22,139
import typing from tml.core.loss_type import LossType from tml.ml_logging.torch_logging import logging import torch def _maybe_warn(reduction: str): _LOSS_TYPE_TO_FUNCTION = { LossType.BCE_WITH_LOGITS: torch.nn.functional.binary_cross_entropy_with_logits } def build_loss( loss_type: LossType, reduction="mean", )...
null
22,140
import typing from tml.core.loss_type import LossType from tml.ml_logging.torch_logging import logging import torch The provided code snippet includes necessary dependencies for implementing the `get_global_loss_detached` function. Write a Python function `def get_global_loss_detached(local_loss, reduction="mean")` to...
Perform all_reduce to obtain the global loss function using the provided reduction. :param local_loss: The local loss of the current rank. :param reduction: The reduction to use for all_reduce. Should match the reduction used by DDP. :return: The reduced & detached global loss.
22,141
import typing from tml.core.loss_type import LossType from tml.ml_logging.torch_logging import logging import torch def _maybe_warn(reduction: str): """ Warning for reduction different than mean. """ if reduction != "mean": logging.warn( f"For the same global_batch_size, the gradient in DDP is guarant...
null
22,142
from abc import abstractmethod from typing import Callable, Dict, List from tml.ml_logging.torch_logging import logging import torch import torchmetrics class MetricMixin: def transform(self, outputs: Dict[str, torch.Tensor]) -> Dict: ... def update(self, outputs: Dict[str, torch.Tensor]): results = self.t...
Returns new class using MetricMixin and given base_metric. Functionally the same using inheritance, just saves some lines of code if no need for class attributes.
22,143
import abc from dataclasses import dataclass, field import logging from typing import ( Any, cast, Dict, Generic, Iterator, List, Optional, Set, Tuple, TypeVar, ) import torch from torch.autograd.profiler import record_function from torch.fx.node import Node from torchrec.distributed.model_parallel ...
null
22,144
import abc from dataclasses import dataclass, field import logging from typing import ( Any, cast, Dict, Generic, Iterator, List, Optional, Set, Tuple, TypeVar, ) import torch from torch.autograd.profiler import record_function from torch.fx.node import Node from torchrec.distributed.model_parallel ...
null
22,145
import abc from dataclasses import dataclass, field import logging from typing import ( Any, cast, Dict, Generic, Iterator, List, Optional, Set, Tuple, TypeVar, ) import torch from torch.autograd.profiler import record_function from torch.fx.node import Node from torchrec.distributed.model_parallel ...
null
22,146
import abc from dataclasses import dataclass, field import logging from typing import ( Any, cast, Dict, Generic, Iterator, List, Optional, Set, Tuple, TypeVar, ) import torch from torch.autograd.profiler import record_function from torch.fx.node import Node from torchrec.distributed.model_parallel ...
null
22,147
import yaml import string import getpass import os from typing import Type from tml.core.config.base_config import BaseConfig The provided code snippet includes necessary dependencies for implementing the `load_config_from_yaml` function. Write a Python function `def load_config_from_yaml(config_type: Type[BaseConfig]...
Recommend method to load a config file (a yaml file) and parse it. Because we have a shared filesystem the recommended route to running jobs it put modified config files with the desired parameters somewhere on the filesytem and run jobs pointing to them.
22,148
import datetime import os from typing import Callable, Dict, Iterable, List, Mapping, Optional from tml.common import log_weights import tml.common.checkpointing.snapshot as snapshot_lib from tml.core.losses import get_global_loss_detached from tml.ml_logging.torch_logging import logging from tml.core.train_pipeline i...
null
22,149
from typing import Any, Dict from tml.core.metric_mixin import MetricMixin, StratifyMixin, TaskMixin import torch import torchmetrics as tm def probs_and_labels( outputs: Dict[str, torch.Tensor], task_idx: int, ) -> Dict[str, torch.Tensor]: preds = outputs["probabilities"] target = outputs["labels"] if task_...
null
22,150
from absl import app, flags import json from typing import Optional import os import sys import torch from tml.common.device import setup_and_get_device from tml.common.utils import setup_configuration import tml.core.custom_training_loop as ctl import tml.machines.environment as env from tml.projects.twhin.models.mode...
null
22,151
from tml.projects.twhin.data.config import TwhinDataConfig from tml.projects.twhin.models.config import TwhinModelConfig from tml.projects.twhin.data.edges import EdgesDataset def create_dataset(data_config: TwhinDataConfig, model_config: TwhinModelConfig): tables = model_config.embeddings.tables table_sizes = {ta...
null
22,152
import functools from tml.projects.twhin.models.config import TwhinModelConfig from tml.projects.twhin.models.models import TwhinModel from tml.optimizers.optimizer import get_optimizer_class, LRShim from tml.optimizers.config import get_optimizer_algorithm_config, LearningRate from tml.ml_logging.torch_logging import ...
Builds an optimizer for a Twhin model combining the embeddings optimizer with an optimizer for per-relation translations. Args: model: TwhinModel to build optimizer for. config: TwhinConfig for model. Returns: Optimizer for model.
22,153
from typing import Callable import math from tml.projects.twhin.data.edges import EdgeBatch from tml.projects.twhin.models.config import TwhinModelConfig from tml.projects.twhin.data.config import TwhinDataConfig from tml.common.modules.embedding.embedding import LargeEmbeddings from tml.optimizers.optimizer import get...
null
22,154
import torch import torchmetrics as tm import tml.core.metrics as core_metrics def create_metrics( device: torch.device, ): metrics = dict() metrics.update( { "AUC": core_metrics.Auc(128), } ) metrics = tm.MetricCollection(metrics).to(device) return metrics
null
22,155
import datetime import os from typing import Callable, List, Optional, Tuple import tensorflow as tf import tml.common.checkpointing.snapshot as snapshot_lib from tml.common.device import setup_and_get_device from tml.core import config as tml_config_mod import tml.core.custom_training_loop as ctl from tml.core import ...
null
22,156
import os import json from absl import app, flags, logging import tensorflow as tf from typing import Dict from tml.projects.home.recap.data import tfe_parsing from tml.core import config as tml_config_mod import tml.projects.home.recap.config as recap_config_mod FLAGS = flags.FLAGS def generate_data(data_path: str, co...
null
22,157
from typing import Mapping, Tuple, Union import torch import torchrec import numpy as np import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `keyed_tensor_from_tensors_dict` function. Write a Python function `def keyed_tensor_from_tensors_dict( tensor_map: Mapping[s...
Convert a dictionary of torch tensor to torchrec keyed tensor Args: tensor_map: Returns:
22,158
from typing import Mapping, Tuple, Union import torch import torchrec import numpy as np import tensorflow as tf def _compute_jagged_tensor_from_tensor(tensor: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: if tensor.is_sparse: x = tensor.coalesce() # Ensure that the indices are ordered. lengths = torch...
Convert a torch tensor to torchrec jagged tensor. Note: Currently only support shape of [Batch_size] or [Batch_size x N] for dense tensors. For sparse tensor the shape of .values() should be [Batch_size] or [Batch_size x N]; the dense_shape of the sparse tensor can be arbitrary. Args: tensor: a torch (sparse) tensor. R...
22,159
from typing import Mapping, Tuple, Union import torch import torchrec import numpy as np import tensorflow as tf def _compute_jagged_tensor_from_tensor(tensor: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: if tensor.is_sparse: x = tensor.coalesce() # Ensure that the indices are ordered. lengths = torch...
Convert a dictionary of (sparse) torch tensors to torchrec keyed jagged tensor. Note: Currently only support shape of [Batch_size] or [Batch_size x 1] for dense tensors. For sparse tensor the shape of .values() should be [Batch_size] or [Batch_size x 1]; the dense_shape of the sparse tensor can be arbitrary. Args: tens...
22,160
from typing import Mapping, Tuple, Union import torch import torchrec import numpy as np import tensorflow as tf def _tf_to_numpy(tf_tensor: tf.Tensor) -> np.ndarray: return tf_tensor._numpy() # noqa def _dense_tf_to_torch(tensor: tf.Tensor, pin_memory: bool) -> torch.Tensor: tensor = _tf_to_numpy(tensor) # Pyto...
null
22,161
import functools import json from tml.projects.home.recap.data import config as recap_data_config from absl import logging import tensorflow as tf def create_tf_example_schema( data_config: recap_data_config.SegDenseSchema, segdense_schema, ): """Generate schema for deseralizing tf.Example. Args: segdense_s...
Placeholder for seg dense. In the future, when we use more seg dense variations, we can change this.
22,162
from tml.projects.home.recap import config as config_mod from absl import logging import tensorflow as tf import numpy as np class TruncateAndSlice(tf.keras.Model): """Class for truncating and slicing.""" def __init__(self, truncate_and_slice_config): super().__init__() self._truncate_and_slice_config = tru...
Builds a preprocess model to apply all preprocessing stages.
22,163
from dataclasses import dataclass from typing import Callable, List, Optional, Tuple, Dict import functools import torch import tensorflow as tf from tml.common.batch import DataclassBatch from tml.projects.home.recap.data.config import RecapDataConfig, TaskData from tml.projects.home.recap.data import preprocessors fr...
Converts a torch data loader output into `RecapBatch`.
22,164
from dataclasses import dataclass from typing import Callable, List, Optional, Tuple, Dict import functools import torch import tensorflow as tf from tml.common.batch import DataclassBatch from tml.projects.home.recap.data.config import RecapDataConfig, TaskData from tml.projects.home.recap.data import preprocessors fr...
Reduce multiple functions into one chained function _chain(x, f1, f2) -> f2(f1(x))
22,165
from dataclasses import dataclass from typing import Callable, List, Optional, Tuple, Dict import functools import torch import tensorflow as tf from tml.common.batch import DataclassBatch from tml.projects.home.recap.data.config import RecapDataConfig, TaskData from tml.projects.home.recap.data import preprocessors fr...
Adds weights based on label sampling for positive and negatives. This is useful for numeric calibration etc. This mutates inputs. Args: inputs: A dictionary of strings to tensor-like structures. tasks: A dict of string (label) to `TaskData` specifying inputs. Returns: A tuple of features and labels; weights are added t...
22,166
from dataclasses import dataclass from typing import Callable, List, Optional, Tuple, Dict import functools import torch import tensorflow as tf from tml.common.batch import DataclassBatch from tml.projects.home.recap.data.config import RecapDataConfig, TaskData from tml.projects.home.recap.data import preprocessors fr...
Compile list of files for training/validation. Used with DataConfigs that use the `explicit_datetime_inputs` format to specify data. For each hour of data, if the directory is missing or empty, we increment a counter to keep track of the number of missing data hours. Returns only files with a `.gz` extension. Args: exp...
22,167
from dataclasses import dataclass from typing import Callable, List, Optional, Tuple, Dict import functools import torch import tensorflow as tf from tml.common.batch import DataclassBatch from tml.projects.home.recap.data.config import RecapDataConfig, TaskData from tml.projects.home.recap.data import preprocessors fr...
null
22,168
from dataclasses import dataclass from typing import Callable, List, Optional, Tuple, Dict import functools import torch import tensorflow as tf from tml.common.batch import DataclassBatch from tml.projects.home.recap.data.config import RecapDataConfig, TaskData from tml.projects.home.recap.data import preprocessors fr...
null
22,169
import bisect from collections import defaultdict import functools import math import typing from typing import Optional import warnings from tml.projects.home.recap import model as model_mod from tml.optimizers import config from tml.optimizers import compute_lr from absl import logging import torch from torchrec.opt...
Builds an optimizer and scheduler. Args: model: A torch model, probably with DDP/DMP. optimizer_config: An OptimizerConfig object that specifies learning rates per tower. Returns: A torch.optim instance, and a scheduler instance.
22,170
from tml.projects.home.recap.model.config import MlpConfig import torch from absl import logging def _init_weights(module): if isinstance(module, torch.nn.Linear): torch.nn.init.xavier_uniform_(module.weight) torch.nn.init.constant_(module.bias, 0)
null
22,171
from __future__ import annotations from absl import logging import torch from typing import Optional, Callable, Mapping, Dict, Sequence, TYPE_CHECKING from tml.projects.home.recap.model import feature_transform from tml.projects.home.recap.model import config as model_config_mod from tml.projects.home.recap.model impor...
null
22,172
from __future__ import annotations from absl import logging import torch from typing import Optional, Callable, Mapping, Dict, Sequence, TYPE_CHECKING from tml.projects.home.recap.model import feature_transform from tml.projects.home.recap.model import config as model_config_mod from tml.projects.home.recap.model impor...
null
22,173
from __future__ import annotations from absl import logging import torch from typing import Optional, Callable, Mapping, Dict, Sequence, TYPE_CHECKING from tml.projects.home.recap.model import feature_transform from tml.projects.home.recap.model import config as model_config_mod from tml.projects.home.recap.model impor...
"Builds a model for a single task
22,174
from __future__ import annotations from absl import logging import torch from typing import Optional, Callable, Mapping, Dict, Sequence, TYPE_CHECKING from tml.projects.home.recap.model import feature_transform from tml.projects.home.recap.model import config as model_config_mod from tml.projects.home.recap.model impor...
null
22,175
from typing import Mapping, Sequence, Union from tml.projects.home.recap.model.config import ( BatchNormConfig, DoubleNormLogConfig, FeaturizationConfig, LayerNormConfig, ) import torch The provided code snippet includes necessary dependencies for implementing the `log_transform` function. Write a Python funct...
Safe log transform that works across both negative, zero, and positive floats.
22,176
from typing import Mapping, Sequence, Union from tml.projects.home.recap.model.config import ( BatchNormConfig, DoubleNormLogConfig, FeaturizationConfig, LayerNormConfig, ) import torch class DoubleNormLog(torch.nn.Module): """Performs a batch norm and clamp on continuous features followed by a layer norm on ...
Trivial right now, but we will change in the future.
22,177
from tml.projects.home.recap.model import config, mlp import torch def _init_weights(module): if isinstance(module, torch.nn.Linear): torch.nn.init.xavier_uniform_(module.weight) torch.nn.init.constant_(module.bias, 0)
null
22,178
from typing import Callable from tml.ml_logging.torch_logging import logging import torch import torch.distributed as dist from torchrec.distributed.model_parallel import DistributedModelParallel The provided code snippet includes necessary dependencies for implementing the `maybe_shard_model` function. Write a Pytho...
Set up and apply DistributedModelParallel to a model if running in a distributed environment. If in a distributed environment, constructs Topology, sharders, and ShardingPlan, then applies DistributedModelParallel. If not in a distributed environment, returns model directly.
22,179
from typing import Callable from tml.ml_logging.torch_logging import logging import torch import torch.distributed as dist from torchrec.distributed.model_parallel import DistributedModelParallel The provided code snippet includes necessary dependencies for implementing the `log_sharded_tensor_content` function. Writ...
Handy function to log the content of EBC embedding layer. Only works for single GPU machines. Args: weight_name: name of tensor, as defined in model table_name: name of the EBC table the weight is taken from weight_tensor: embedding weight tensor
22,180
import yaml import getpass import os import string from typing import Tuple, Type, TypeVar from tml.core.config import base_config import fsspec C = TypeVar("C", bound=base_config.BaseConfig) def _read_file(f): with fsspec.open(f) as f: return f.read() The provided code snippet includes necessary dependencies fo...
Resolves a config at a yaml path. Args: config_type: Pydantic config class to load. yaml_path: yaml path of the config file. substitute_env_variable: If True substitute string in the format $VAR or ${VAR} by their environment variable value whenever possible. If an environment variable doesn't exist, the string is left...
22,181
import os import subprocess import sys from typing import Optional from tml.ml_logging.torch_logging import logging from twitter.ml.tensorflow.experimental.distributed import utils import torch import torch.distributed.run def is_distributed_worker(): world_size = os.environ.get("WORLD_SIZE", None) rank = os.envir...
Wrapper function for single node, multi-GPU Pytorch training. If the necessary distributed Pytorch environment variables (WORLD_SIZE, RANK) have been set, then this function executes `train_fn(**training_kwargs)`. Otherwise, this function calls torchrun and points at the calling module `module_name`. After this call, t...
22,182
import os import time from typing import Any, Dict, List, Optional from tml.ml_logging.torch_logging import logging from tml.common.filesystem import infer_fs, is_gcs_fs import torchsnapshot def _eval_done_path(checkpoint_path: str, eval_partition: str) -> str: return os.path.join(_eval_subdir(checkpoint_path), f"{ev...
null
22,183
import os import time from typing import Any, Dict, List, Optional from tml.ml_logging.torch_logging import logging from tml.common.filesystem import infer_fs, is_gcs_fs import torchsnapshot def is_done_eval(checkpoint_path: str, eval_partition: str): return get_checkpoint(checkpoint_path).exists(_eval_done_path(chec...
null
22,184
import itertools from typing import Callable, Dict, List, Optional, Union from tml.ml_logging.torch_logging import logging import torch import torch.distributed as dist from torchrec.distributed.model_parallel import DistributedModelParallel The provided code snippet includes necessary dependencies for implementing t...
Creates dict of reduced weights to log to give sense of training. Args: model: model to traverse. how_to_log: if a function, then applies this to every parameter, if a dict then only applies and logs specified parameters.
22,185
import itertools from typing import Callable, Dict, List, Optional, Union from tml.ml_logging.torch_logging import logging import torch import torch.distributed as dist from torchrec.distributed.model_parallel import DistributedModelParallel The provided code snippet includes necessary dependencies for implementing t...
Logs the norms of the embedding tables as specified by ebc_keys. As of now, log average norm per rank. Args: model_state_dict: model.state_dict() ebc_keys: list of embedding keys from state_dict to log. Must contain full name, i.e. model.embeddings.ebc.embedding_bags.meta__user_id.weight sample_size: Limits number of r...
22,186
from fsspec.implementations.local import LocalFileSystem import gcsfs GCS_FS = gcsfs.GCSFileSystem(cache_timeout=-1) LOCAL_FS = LocalFileSystem() def infer_fs(path: str): if path.startswith("gs://"): return GCS_FS elif path.startswith("hdfs://"): # We can probably use pyarrow HDFS to support this. rais...
null
22,187
from fsspec.implementations.local import LocalFileSystem import gcsfs LOCAL_FS = LocalFileSystem() def is_local_fs(fs): return fs == LOCAL_FS
null
22,188
from fsspec.implementations.local import LocalFileSystem import gcsfs GCS_FS = gcsfs.GCSFileSystem(cache_timeout=-1) def is_gcs_fs(fs): return fs == GCS_FS
null
22,189
import os import torch import torch.distributed as dist def maybe_setup_tensorflow(): try: import tensorflow as tf except ImportError: pass else: tf.config.set_visible_devices([], "GPU") # disable tf gpu def setup_and_get_device(tf_ok: bool = True) -> torch.device: if tf_ok: maybe_setup_tensor...
null
22,190
import logging as py_logging import sys from absl import logging as logging The provided code snippet includes necessary dependencies for implementing the `setup_absl_logging` function. Write a Python function `def setup_absl_logging()` to solve the following problem: Make sure that absl logging pushes to stdout rathe...
Make sure that absl logging pushes to stdout rather than stderr.
22,191
import functools from typing import Optional from tml.ml_logging.absl_logging import logging as logging from absl import logging as absl_logging import torch.distributed as dist The provided code snippet includes necessary dependencies for implementing the `rank_specific` function. Write a Python function `def rank_sp...
Ensures that we only override a given logger once.
22,192
from typing import List, Optional from tml.common.filesystem import infer_fs import fire import pandas as pd import pyarrow as pa import pyarrow.dataset as pads import pyarrow.parquet as pq def _create_dataset(path: str): fs = infer_fs(path) files = fs.glob(path) return pads.dataset(files, format="parquet", file...
null
22,193
import json import os from typing import List def get_task_type(): if on_kf(): return os.environ["SPEC_TYPE"] return os.environ["TASK_TYPE"] def is_chief() -> bool: return get_task_type() == "chief"
null
22,194
import json import os from typing import List def get_task_type(): if on_kf(): return os.environ["SPEC_TYPE"] return os.environ["TASK_TYPE"] def is_reader() -> bool: return get_task_type() == "datasetworker"
null
22,195
import json import os from typing import List def get_task_type(): if on_kf(): return os.environ["SPEC_TYPE"] return os.environ["TASK_TYPE"] def is_dispatcher() -> bool: return get_task_type() == "datasetdispatcher"
null
22,196
import json import os from typing import List def has_readers(): if on_kf(): machines_config_env = json.loads(os.environ["MACHINES_CONFIG"]) return machines_config_env["dataset_worker"] is not None return os.environ.get("HAS_READERS", "False") == "True" def get_dds_dispatcher_address(): if not has_readers...
null
22,197
import json import os from typing import List def on_kf(): return "SPEC_TYPE" in os.environ def has_readers(): if on_kf(): machines_config_env = json.loads(os.environ["MACHINES_CONFIG"]) return machines_config_env["dataset_worker"] is not None return os.environ.get("HAS_READERS", "False") == "True" def ge...
null
22,198
import json import os from typing import List FLIGHT_SERVER_PORT: int = 2222 def on_kf(): return "SPEC_TYPE" in os.environ def get_num_readers(): if not has_readers(): return 0 if on_kf(): machines_config_env = json.loads(os.environ["MACHINES_CONFIG"]) return int(machines_config_env["num_dataset_worke...
null
22,199
import json import os from typing import List def get_dds_journaling_dir(): return os.environ.get("DATASET_JOURNALING_DIR", None)
null
22,200
import sys import logging def is_venv(): # See https://stackoverflow.com/questions/1871549/determine-if-python-is-running-inside-virtualenv return sys.base_prefix != sys.prefix def _main(): if is_venv(): logging.info("In venv %s", sys.prefix) sys.exit(0) else: logging.error("Not in venv") sys.e...
null
22,201
from typing import Optional, Union, List, Tuple import numpy as np import matplotlib as mpl from matplotlib.path import Path from matplotlib.lines import Line2D import matplotlib.pyplot as plt import matplotlib.colors as mcolors from matplotlib.patches import Polygon def make_lines_glow( ax: Optional[plt.Axes] = No...
Add a glow effect to the lines in an axis object and an 'underglow' effect below the line.
22,202
from typing import Optional, Union, List, Tuple import numpy as np import matplotlib as mpl from matplotlib.path import Path from matplotlib.lines import Line2D import matplotlib.pyplot as plt import matplotlib.colors as mcolors from matplotlib.patches import Polygon The provided code snippet includes necessary depend...
Add glow effect to dots in scatter plot. Each plot is redrawn 10 times with increasing width to create glow effect.
22,203
from typing import Optional, Union, List, Tuple import numpy as np import matplotlib as mpl from matplotlib.path import Path from matplotlib.lines import Line2D import matplotlib.pyplot as plt import matplotlib.colors as mcolors from matplotlib.patches import Polygon The provided code snippet includes necessary depend...
Replace each bar with a rectangle filled with a color gradient going transparent
22,204
import re from typing import List, Optional, Any from langchain.text_splitter import RecursiveCharacterTextSplitter import logging def _split_text_with_regex_from_end( text: str, separator: str, keep_separator: bool ) -> List[str]: # Now that we have the separator, split the text if separator: ...
null
22,205
from langchain.docstore.document import Document import re def is_possible_title( text: str, title_max_word_length: int = 20, non_alpha_threshold: float = 0.5, ) -> bool: """Checks to see if the text passes all of the checks for a valid title. Parameters ---------- text T...
null
22,206
from typing import TYPE_CHECKING def get_ocr(use_cuda: bool = True) -> "RapidOCR": try: from rapidocr_paddle import RapidOCR ocr = RapidOCR(det_use_cuda=use_cuda, cls_use_cuda=use_cuda, rec_use_cuda=use_cuda) except ImportError: from rapidocr_onnxruntime import RapidOCR ocr = Ra...
null
22,207
from pathlib import PathSCORE_THRESHOLD, import httpx import contextlib import json import os from io import BytesIO from server.utils import set_httpx_config, api_address, get_httpx_client from pprint import pprint from langchain_core._api import deprecated The provided code snippet includes necessary dependencies fo...
return error message if error occured when requests API
22,208
from pathlib import PathSCORE_THRESHOLD, import httpx import contextlib import json import os from io import BytesIO from server.utils import set_httpx_config, api_address, get_httpx_client from pprint import pprint from langchain_core._api import deprecated The provided code snippet includes necessary dependencies fo...
return error message if error occured when requests API
22,209
import streamlit as st from webui_pages.utils import * from st_aggrid import AgGrid, JsCode from st_aggrid.grid_options_builder import GridOptionsBuilder import pandas as pd from server.knowledge_base.utils import get_file_path, LOADER_DICT from server.knowledge_base.kb_service.base import get_kb_details, get_kb_file_d...
null
22,210
import streamlit as st from webui_pages.utils import * def model_config_page(api: ApiRequest): pass
null
22,211
import streamlit as st from webui_pages.utils import * from streamlit_chatbox import * from streamlit_modal import Modal from datetime import datetime import os import re import time from configs import (TEMPERATURE, HISTORY_LEN, PROMPT_TEMPLATES, LLM_MODELS, DEFAULT_KNOWLEDGE_BASE, DEFAULT_SEARCH_...
null
22,212
def get_latest_tag(): output = subprocess.check_output(['git', 'tag']) tags = output.decode('utf-8').split('\n')[:-1] latest_tag = sorted(tags, key=lambda t: tuple(map(int, re.match(r'v(\d+)\.(\d+)\.(\d+)', t).groups())))[-1] return latest_tag
null
22,213
def update_version_number(latest_tag, increment): major, minor, patch = map(int, re.match(r'v(\d+)\.(\d+)\.(\d+)', latest_tag).groups()) if increment == 'X': major += 1 minor, patch = 0, 0 elif increment == 'Y': minor += 1 patch = 0 elif increment == 'Z': patch ...
null
22,214
import asyncio import multiprocessing as mp import os import subprocess import sys from multiprocessing import Process from datetime import datetime from pprint import pprint from langchain_core._api import deprecated sys.path.append(os.path.dirname(os.path.dirname(__file__))) from configs import ( LOG_PATH, lo...
null
22,215
import sys import os import torch from datetime import datetime from configs import ( MODEL_PATH, EMBEDDING_MODEL, EMBEDDING_KEYWORD_FILE, ) from safetensors.torch import save_model from sentence_transformers import SentenceTransformer from langchain_core._api import deprecated def add_keyword_to_model(mode...
null
22,216
import sys import os import subprocess import re import logging import argparse LOG_PATH = "./logs/" base_check_sh = """while [ `grep -c "Uvicorn running on" {0}/{1}.log` -eq '0' ];do sleep 5s; echo "wait {2} running" done echo '{2} running...
null
22,217
import nltk import sys import os from configs import VERSION from configs.model_config import NLTK_DATA_PATH from configs.server_config import OPEN_CROSS_DOMAIN import argparse import uvicorn from fastapi import Body from fastapi.middleware.cors import CORSMiddleware from starlette.responses import RedirectResponse fro...
null
22,218
def torch_gc(): try: import torch if torch.cuda.is_available(): # with torch.cuda.device(DEVICE): torch.cuda.empty_cache() torch.cuda.ipc_collect() elif torch.backends.mps.is_available(): try: from torch.mps import empty_cache...
null