id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
7,781
import math import warnings from typing import Optional import torch import torch.nn as nn from einops import rearrange from packaging import version from torch import nn from .norm import LPLayerNorm def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id): if attn_impl == "flas...
null
7,782
import math import warnings from typing import Optional import torch import torch.nn as nn from einops import rearrange from packaging import version from torch import nn from .norm import LPLayerNorm def build_alibi_bias(n_heads, seq_len, full=False, alibi_bias_max=8, device=None, dtype=None): alibi_bias = torch.a...
null
7,783
import torch def _cast_if_autocast_enabled(tensor): if torch.is_autocast_enabled(): if tensor.device.type == "cuda": dtype = torch.get_autocast_gpu_dtype() elif tensor.device.type == "cpu": dtype = torch.get_autocast_cpu_dtype() else: raise NotImplemented...
null
7,785
import math import torch import triton_pre_mlir as triton import triton_pre_mlir.language as tl def init_to_zero(name): return lambda nargs: nargs[name].zero_()
null
7,786
import math import torch import triton_pre_mlir as triton import triton_pre_mlir.language as tl def _fwd_kernel( Q, K, V, Bias, Out, Lse, TMP, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride...
null
7,787
import math import torch import triton_pre_mlir as triton import triton_pre_mlir.language as tl def _bwd_preprocess_do_o_dot( Out, DO, Delta, stride_ob, stride_oh, stride_om, stride_dob, stride_doh, stride_dom, nheads, seqlen_q, seqlen_q_rounded, headdim, BLOCK_M:...
null
7,788
from contextlib import contextmanager import torch import torch.nn as nn def init_on_device(device: torch.device, include_buffers: bool = False): """Device initialization context manager. A context manager under which models are initialized with all parameters on the specified device. Args: devi...
Meta initialization context manager. A context manager under which models are initialized with all parameters on the meta device, therefore creating an empty model. Useful when just initializing the model would blow the available RAM. Args: include_buffers (`bool`, *optional*, defaults to `False`): Whether or not to al...
7,789
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn from .norm import NORM_CLASS_REGISTRY def torch_default_param_init_fn_(module: nn.Module, verbose: int = 0, **kwargs): del kwargs if verbose...
null
7,790
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn from .norm import NORM_CLASS_REGISTRY def _normal_param_init_fn_( module: nn.Module, std: float, n_layers: int, d_model: Optional[int...
null
7,791
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn from .norm import NORM_CLASS_REGISTRY def small_param_init_fn_( module: nn.Module, n_layers: int, d_model: int, init_div_is_residual:...
From section 2.3.1 of GPT-NeoX-20B: An Open-Source AutoregressiveLanguage Model — Black et. al. (2022) see https://github.com/EleutherAI/gpt-neox/blob/9610391ab319403cef079b438edd016a2443af54/megatron/model/init_functions.py#L151 and https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/transformer.py
7,792
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn from .norm import NORM_CLASS_REGISTRY def generic_param_init_fn_( module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int] ...
null
7,793
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn from .norm import NORM_CLASS_REGISTRY def generic_param_init_fn_( module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int] ...
null
7,794
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn from .norm import NORM_CLASS_REGISTRY def generic_param_init_fn_( module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int] ...
null
7,795
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn from .norm import NORM_CLASS_REGISTRY def generic_param_init_fn_( module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int] ...
null
7,796
import math import warnings from types import MethodType from typing import Any, Dict, List, Optional, Tuple, Union import torch from transformers.models.bloom.modeling_bloom import ( BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEnt...
Converts a HuggingFace Causal LM to a Prefix LM. Supported HuggingFace model classes: - `GPT2LMHeadModel` - `GPTNeoForCausalLM` - `GPTNeoXForCausalLM` - `GPTJForCausalLM` - `BloomForCausalLM` - `OPTForCausalLM` Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the `generate` method ...
7,797
import math import warnings from types import MethodType from typing import Any, Dict, List, Optional, Tuple, Union import torch from transformers.models.bloom.modeling_bloom import ( BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEnt...
Attempts to add bidirectional_mask to batch if missing. Raises: KeyError if bidirectional_mask is missing and can't be inferred
7,798
from typing import Union from transformers import AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] NUM_SENTINEL_TOKENS: int = 100 The provided code snippet includes necessary dependencies for implementing the `adapt_tokenizer_for_denoising` fun...
Adds sentinel tokens and padding token (if missing). Expands the tokenizer vocabulary to include sentinel tokens used in mixture-of-denoiser tasks as well as a padding token. All added tokens are added as special tokens. No tokens are added if sentinel tokens and padding token already exist.
7,799
import argparse import os import torch from modeling_otter import OtterForConditionalGeneration class OtterForConditionalGeneration(OtterPreTrainedModel): def __init__( self, config: OtterConfig, ): def get_input_embeddings(self) -> nn.Module: def set_input_embeddings(sel...
null
7,800
import random import sys from typing import List, Optional import torch import torch.distributed as dist import torch.nn as nn from accelerate.hooks import AlignDevicesHook, add_hook_to_module from einops import rearrange, repeat from peft import LoraConfig, TaskType, get_peft_model from transformers.modeling_outputs i...
null
7,801
import random import sys from typing import List, Optional import torch import torch.distributed as dist import torch.nn as nn from accelerate.hooks import AlignDevicesHook, add_hook_to_module from einops import rearrange, repeat from peft import LoraConfig, TaskType, get_peft_model from transformers.modeling_outputs i...
Apply mixins to a class instance after creation
7,802
import random import sys from typing import List, Optional import torch import torch.distributed as dist import torch.nn as nn from accelerate.hooks import AlignDevicesHook, add_hook_to_module from einops import rearrange, repeat from peft import LoraConfig, TaskType, get_peft_model from transformers.modeling_outputs i...
Set nested attribute of obj Example: setattr_recursive(obj, 'a.b.c', val) is equivalent to obj.a.b.c = val
7,803
import random import sys from typing import List, Optional import torch import torch.distributed as dist import torch.nn as nn from accelerate.hooks import AlignDevicesHook, add_hook_to_module from einops import rearrange, repeat from peft import LoraConfig, TaskType, get_peft_model from transformers.modeling_outputs i...
null
7,804
import re import argparse import os import torch import torch.nn as nn from transformers import CLIPVisionModel, LlamaForCausalLM, LlamaTokenizer from otter_ai.models.otter.modeling_otter import ( OtterPreTrainedModel, OtterLMMixin, extend_instance, _infer_decoder_layers_attr_name, OtterPerceiverRes...
null
7,805
import argparse import os import torch from modeling_otter import OtterForConditionalGeneration class OtterForConditionalGeneration(OtterPreTrainedModel): config_class = OtterConfig def __init__( self, config: OtterConfig, ): super().__init__(config) ### TODO: give "LlamaFo...
null
7,806
import re import argparse import os import torch import torch.nn as nn from transformers import CLIPVisionModel, LlamaForCausalLM, LlamaTokenizer from otter_ai.models.otter.modeling_otter import ( OtterPreTrainedModel, OtterLMMixin, extend_instance, _infer_decoder_layers_attr_name, OtterPerceiverRes...
null
7,807
import math import warnings from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss from torch.nn import functional as F from transformers.modeling_outputs import ( BaseModelOutputWithPastA...
null
7,808
import math import warnings from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss from torch.nn import functional as F from transformers.modeling_outputs import ( BaseModelOutputWithPastA...
null
7,809
import math import warnings from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss from torch.nn import functional as F from transformers.modeling_outputs import ( BaseModelOutputWithPastA...
null
7,810
import math import warnings from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss from torch.nn import functional as F from transformers.modeling_outputs import ( BaseModelOutputWithPastA...
null
7,811
import math import warnings from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss from torch.nn import functional as F from transformers.modeling_outputs import ( BaseModelOutputWithPastA...
null
7,812
import math import warnings from typing import Optional import torch import torch.nn as nn from einops import rearrange from torch import nn from .low_precision_layernorm import LPLayerNorm def scaled_multihead_dot_product_attention( query, key, value, n_heads, softmax_scale=None, attn_bias=Non...
null
7,813
import math import warnings from typing import Optional import torch import torch.nn as nn from einops import rearrange from torch import nn from .low_precision_layernorm import LPLayerNorm def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool): def check_valid_inputs(*tensors, valid...
null
7,814
import math import warnings from typing import Optional import torch import torch.nn as nn from einops import rearrange from torch import nn from .low_precision_layernorm import LPLayerNorm def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool): if original_is_causal and num_quer...
null
7,815
import math import warnings from typing import Optional import torch import torch.nn as nn from einops import rearrange from torch import nn from .low_precision_layernorm import LPLayerNorm def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id): if attn_impl == "flash": ...
null
7,816
import math import warnings from typing import Optional import torch import torch.nn as nn from einops import rearrange from torch import nn from .low_precision_layernorm import LPLayerNorm def alibi_bias(n_heads, seq_len, full=False, alibi_bias_max=8, device=None, dtype=None): def attn_bias(attn_impl, attn_bias, n_he...
null
7,817
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn def torch_default_param_init_fn_( module: nn.Module, verbose: int = 0, **kwargs, ): del kwargs # unused, just to capture any extra ...
null
7,818
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn def _normal_param_init_fn_( module: nn.Module, std: float, n_layers: int, d_model: Optional[int] = None, init_div_is_residual: Un...
null
7,819
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn def small_param_init_fn_( module: nn.Module, n_layers: int, d_model: int, init_div_is_residual: Union[int, float, str, bool] = True, ...
From section 2.3.1 of GPT-NeoX-20B: An Open-Source AutoregressiveLanguage Model — Black et. al. (2022) see https://github.com/EleutherAI/gpt-neox/blob/9610391ab319403cef079b438edd016a2443af54/megatron/model/init_functions.py#L151 and https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/transformer.py
7,820
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn def generic_param_init_fn_( module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int] = None, init_div_is_residual: Unio...
null
7,821
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn def generic_param_init_fn_( module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int] = None, init_div_is_residual: Unio...
null
7,822
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn def generic_param_init_fn_( module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int] = None, init_div_is_residual: Unio...
null
7,823
import math import warnings from collections.abc import Sequence from functools import partial from typing import Optional, Tuple, Union import torch from torch import nn def generic_param_init_fn_( module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int] = None, init_div_is_residual: Unio...
null
7,824
import torch import torch.nn.functional as F def _cast_if_autocast_enabled(tensor): if torch.is_autocast_enabled(): if tensor.device.type == "cuda": dtype = torch.get_autocast_gpu_dtype() elif tensor.device.type == "cpu": dtype = torch.get_autocast_cpu_dtype() else: ...
null
7,825
import math from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from flash_attn.ops.layer_norm import layer_norm as fused_layer_norm from flash_attn.ops.fused_dense import fused_mlp_func from fl...
Make causal mask used for bi-directional self-attention.
7,826
import math from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from flash_attn.ops.layer_norm import layer_norm as fused_layer_norm from flash_attn.ops.fused_dense import fused_mlp_func from fl...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
7,827
import math from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from flash_attn.ops.layer_norm import layer_norm as fused_layer_norm from flash_attn.ops.fused_dense import fused_mlp_func from fl...
null
7,828
import re from typing import Dict, List, Optional, Tuple, Union import numpy as np from transformers.processing_utils import ProcessorMixin from transformers.utils import TensorType, is_torch_available, logging, requires_backends from transformers.tokenization_utils_base import TruncationStrategy, PaddingStrategy The ...
Takes an unpacked stream of tokens (i.e. a list of tensors, one for each item in the batch) and does the required padding to create a single tensor for the batch of shape batch_size x new_seq_len.
7,829
import re from typing import Dict, List, Optional, Tuple, Union import numpy as np from transformers.processing_utils import ProcessorMixin from transformers.utils import TensorType, is_torch_available, logging, requires_backends from transformers.tokenization_utils_base import TruncationStrategy, PaddingStrategy The ...
Takes an input_stream tensor of shape B x S x ?. For each subsequence, adds any required padding to account for images and then unpacks the subsequences to create a single sequence per item in the batch. Returns a list of tensors, one for each item in the batch.
7,830
import re from typing import Dict, List, Optional, Tuple, Union import numpy as np from transformers.processing_utils import ProcessorMixin from transformers.utils import TensorType, is_torch_available, logging, requires_backends from transformers.tokenization_utils_base import TruncationStrategy, PaddingStrategy logge...
Given a set of prompts and number of tokens to generate: - tokenize prompts - set the sequence length to be the max of length of prompts plus the number of tokens we would like to generate - pad all the sequences to this length so we can convert them into a 3D tensor.
7,831
import re import torch The provided code snippet includes necessary dependencies for implementing the `rename_flamingo_checkpoint` function. Write a Python function `def rename_flamingo_checkpoint(old_ckpt: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]` to solve the following problem: Rename some keys in the pub...
Rename some keys in the public flamingo checkpoint
7,832
import random from dataclasses import dataclass from typing import Callable, Optional import torch import torch.nn as nn from accelerate.hooks import AlignDevicesHook, add_hook_to_module from einops import rearrange, repeat from transformers import CLIPVisionModel, LlamaForCausalLM, LlamaTokenizer from transformers.mod...
null
7,833
import random from dataclasses import dataclass from typing import Callable, Optional import torch import torch.nn as nn from accelerate.hooks import AlignDevicesHook, add_hook_to_module from einops import rearrange, repeat from transformers import CLIPVisionModel, LlamaForCausalLM, LlamaTokenizer from transformers.mod...
Apply mixins to a class instance after creation
7,834
import random from dataclasses import dataclass from typing import Callable, Optional import torch import torch.nn as nn from accelerate.hooks import AlignDevicesHook, add_hook_to_module from einops import rearrange, repeat from transformers import CLIPVisionModel, LlamaForCausalLM, LlamaTokenizer from transformers.mod...
Set nested attribute of obj Example: setattr_recursive(obj, 'a.b.c', val) is equivalent to obj.a.b.c = val
7,835
import random from dataclasses import dataclass from typing import Callable, Optional import torch import torch.nn as nn from accelerate.hooks import AlignDevicesHook, add_hook_to_module from einops import rearrange, repeat from transformers import CLIPVisionModel, LlamaForCausalLM, LlamaTokenizer from transformers.mod...
null
7,836
import re import argparse import os import torch import torch.nn as nn from transformers import CLIPVisionModel, LlamaForCausalLM, LlamaTokenizer import sys from modeling_flamingo import FlamingoForConditionalGeneration from configuration_flamingo import FlamingoConfig class FlamingoForConditionalGeneration(FlamingoPr...
null
7,837
import re import argparse import os import torch import torch.nn as nn from transformers import CLIPVisionModel, LlamaForCausalLM, LlamaTokenizer import sys from ..configuration_flamingo import FlamingoConfig from ..modeling_flamingo import FlamingoForConditionalGeneration class FlamingoForConditionalGeneration(Flamin...
null
7,838
from abc import ABC, abstractmethod from typing import List, Dict, Any, Tuple import importlib AVAILABLE_DATASETS: List[str] = [ "change.SpotTheDifference", "change.CocoGeneralDifference", "video.DenseCaptions", "video.TVCaptions", "video.VisualStoryTelling", "3d.SceneNavigation", "fpv.EGO4D...
Get an instance of a dataset class based on the given path. Args: path (str): The path to the dataset class in the format "<module>.<class>". dataset_args (Dict[str, str]): Additional arguments to pass to the dataset class constructor. Returns: AbstractDataset: An instance of the dataset class. Raises: AssertionError: ...
7,839
from abc import ABC, abstractmethod from typing import List, Dict, Any, Tuple import importlib AVAILABLE_DATASETS: List[str] = [ "change.SpotTheDifference", "change.CocoGeneralDifference", "video.DenseCaptions", "video.TVCaptions", "video.VisualStoryTelling", "3d.SceneNavigation", "fpv.EGO4D...
Get a list of available dataset paths. Returns: List[str]: A list of available dataset paths.
7,840
import base64 import os from concurrent.futures import ThreadPoolExecutor from io import BytesIO from typing import Generator, Tuple import cv2 from PIL import Image from tqdm import tqdm def get_image_id(image_name: str, dataset_name: str) -> str: """ Extracts the image identifier from a given image name. ...
Converts a dictionary of images to a JSON-compatible dictionary with base64 encoded strings. This generator function will yield the processed image data one at a time, allowing you to write the results to a file without needing to store the entire dictionary in memory. Args: images (Dict[str, bytes]): A dictionary of i...
7,841
import base64 import os from concurrent.futures import ThreadPoolExecutor from io import BytesIO from typing import Generator, Tuple import cv2 from PIL import Image from tqdm import tqdm def process_image(image: bytes, target_size=(224, 224)) -> bytes: """ Processes the input image by resizing it, converting i...
Extracts frames from a video file at a specified frame rate and returns them as base64 encoded strings. Args: video_file (str): The path to the video file. fps (int): The frame rate at which frames should be extracted. Defaults to 1 frame per second. Returns: List[bytes]: A list of byte strings representing the extract...
7,842
import json import requests from tqdm import tqdm from concurrent.futures import ThreadPoolExecutor from image_utils import resize_image, create_folder def download_single_image(image: dict[str]) -> tuple[str, bytes]: """ Download a single image and resize it. Args: image: A dictionary containing im...
Download multiple images concurrently using thread pooling. Args: images: A list of dictionaries, each containing image information. num_threads: The number of threads to use for concurrent downloading. Returns: A dictionary mapping image IDs to their corresponding resized images as bytes.
7,843
import os from glob import glob from tqdm import tqdm from concurrent.futures import ThreadPoolExecutor from image_utils import process_image def process(cur_dir, img_root): """ Process images in a directory. Args: cur_dir (str): The name of the current directory. img_root (str): The root di...
Process images in parallel using multiple threads. Args: img_root (str): The root directory of the images. num_threads (int): The number of threads to use for parallel processing. Returns: dict: A dictionary containing processed images. The keys are unique identifiers for each image, and the values are the processed im...
7,844
from abc import ABC, abstractmethod from typing import List, Dict, Any, Union import importlib import json AVAILABLE_DATASETS: List[str] = [ "change.SpotTheDifference", "change.CocoSpotTheDifference", "video.DenseCaptions", "video.TVCaptions", "video.VisualStoryTelling", "3d.SceneNavigation", ...
null
7,845
from abc import ABC, abstractmethod from typing import List, Dict, Any, Union import importlib import json AVAILABLE_DATASETS: List[str] = [ "change.SpotTheDifference", "change.CocoSpotTheDifference", "video.DenseCaptions", "video.TVCaptions", "video.VisualStoryTelling", "3d.SceneNavigation", ...
null
7,846
import os import argparse import time from concurrent.futures import ThreadPoolExecutor from typing import Dict, List, Union import openai from tqdm import tqdm from abstract_dataset import get_dataset_by_path from file_utils import ( save_query_json, export_output_json, format_output, query_gpt, ) def...
null
7,847
import os import argparse import time from concurrent.futures import ThreadPoolExecutor from typing import Dict, List, Union import openai from tqdm import tqdm from abstract_dataset import get_dataset_by_path from file_utils import ( save_query_json, export_output_json, format_output, query_gpt, ) def...
null
7,848
import json import os import time import openai import random from litellm import completion The provided code snippet includes necessary dependencies for implementing the `split_question_and_answer` function. Write a Python function `def split_question_and_answer(pair_of_answer: str, file_id: str) -> tuple[bool, dict...
Split the question and answer from the pair of question and answer. Args: pair_of_answer (str): the pair of question and answer. file_id (str): the id of the file.
7,849
import json import os import time import openai import random from litellm import completion The provided code snippet includes necessary dependencies for implementing the `export_single_output_json` function. Write a Python function `def export_single_output_json(result: dict[str, str], file_name: str, dataset_name: ...
Export the output of ChatGPT to a json file. Args:
7,850
import json import os import time import openai import random from litellm import completion The provided code snippet includes necessary dependencies for implementing the `export_output_json` function. Write a Python function `def export_output_json(results: list[dict[str, str]], name: str, duration: float) -> None` ...
Export the output of ChatGPT to a json file. Args:
7,851
import json import os import time import openai import random from litellm import completion The provided code snippet includes necessary dependencies for implementing the `save_query_json` function. Write a Python function `def save_query_json(inputs: dict[str], name: str) -> None` to solve the following problem: Sav...
Save the query json to a file. Args: inputs (dict[str]): the inputs to query the GPT API. name (str): the name of the file.
7,852
from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPas...
Make causal mask used for bi-directional self-attention.
7,853
from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPas...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
7,854
from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPas...
null
7,855
import random import torch import torchvision.transforms as T import torchvision.transforms.functional as F import numpy as np from PIL import Image def crop(image, target, region, delete=True): cropped_image = F.crop(image, *region) target = target.copy() i, j, h, w = region # should we do something...
null
7,856
import random import torch import torchvision.transforms as T import torchvision.transforms.functional as F import numpy as np from PIL import Image def hflip(image, target): flipped_image = F.hflip(image) w, h = image.size target = target.copy() if "boxes" in target: boxes = target["boxes"] ...
null
7,857
import random import torch import torchvision.transforms as T import torchvision.transforms.functional as F import numpy as np from PIL import Image def resize(image, target, size, max_size=None): # size can be min_size (scalar) or (w, h) tuple def get_size_with_aspect_ratio(image_size, size, max_size=None): ...
null
7,858
import base64 import contextlib import os import random import re import sys from io import BytesIO import pandas as pd import numpy as np import pyarrow.parquet as pq import orjson import torch from PIL import Image, ImageFile from prettytable import PrettyTable from torch.utils.data import Dataset from torchvision im...
Context manager which seeds the NumPy PRNG with the specified seed and restores the state afterward
7,859
import base64 import contextlib import os import random import re import sys from io import BytesIO import pandas as pd import numpy as np import pyarrow.parquet as pq import orjson import torch from PIL import Image, ImageFile from prettytable import PrettyTable from torch.utils.data import Dataset from torchvision im...
null
7,860
import base64 import contextlib import os import random import re import sys from io import BytesIO import pandas as pd import numpy as np import pyarrow.parquet as pq import orjson import torch from PIL import Image, ImageFile from prettytable import PrettyTable from torch.utils.data import Dataset from torchvision im...
null
7,861
import base64 import contextlib import os import random import re import sys from io import BytesIO import pandas as pd import numpy as np import pyarrow.parquet as pq import orjson import torch from PIL import Image, ImageFile from prettytable import PrettyTable from torch.utils.data import Dataset from torchvision im...
null
7,862
import ast import functools import io import json import logging import math import os import random import statistics import sys from dataclasses import dataclass from multiprocessing import Value import braceexpand import numpy as np import torch import torch.utils import torchvision import webdataset as wds import y...
null
7,863
import ast import functools import io import json import logging import math import os import random import statistics import sys from dataclasses import dataclass from multiprocessing import Value import braceexpand import numpy as np import torch import torch.utils import torchvision import webdataset as wds import y...
get dataloader worker seed from pytorch
7,864
import ast import functools import io import json import logging import math import os import random import statistics import sys from dataclasses import dataclass from multiprocessing import Value import braceexpand import numpy as np import torch import torch.utils import torchvision import webdataset as wds import y...
null
7,865
import argparse import torch from transformers import AutoTokenizer, AutoModelForCausalLM from pipeline.serve.conversation import conv_templates, SeparatorStyle The provided code snippet includes necessary dependencies for implementing the `generate_stream` function. Write a Python function `def generate_stream(tokeni...
Adapted from fastchat/serve/model_worker.py::generate_stream
7,866
import logging import logging.handlers import os import sys handler = None class StreamToLogger(object): """ Fake file-like stream object that redirects writes to a logger instance. """ def __init__(self, logger, log_level=logging.INFO): self.terminal = sys.stdout self.logger = logger ...
null
7,867
import dataclasses from enum import auto, Enum from typing import List, Tuple import io import base64 import os from PIL import Image import copy def decode_image(encoded_image: str) -> Image: decoded_bytes = base64.b64decode(encoded_image.encode("utf-8")) buffer = io.BytesIO(decoded_bytes) image = Image.o...
null
7,868
from flask import Flask, request, jsonify from PIL import Image import torch from transformers import AutoTokenizer, FuyuForCausalLM, FuyuProcessor, FuyuImageProcessor import base64 import re from io import BytesIO from datetime import datetime import hashlib from PIL import Image import io, os prompt_txt_path = "../us...
null
7,869
import os import datetime import json import base64 from PIL import Image import gradio as gr import hashlib import requests from utils import build_logger from conversation import model import io def decode_image(encoded_image: str) -> Image: decoded_bytes = base64.b64decode(encoded_image.encode("utf-8")) buf...
null
7,870
import os import datetime import json import base64 from PIL import Image import gradio as gr import hashlib import requests from utils import build_logger from conversation import model import io LOGDIR = "log" def get_conv_log_filename(): t = datetime.datetime.now() name = os.path.join(LOGDIR, f"{t.year}-{t....
null
7,871
import os import datetime import json import base64 from PIL import Image import gradio as gr import hashlib import requests from utils import build_logger from conversation import model import io logger = build_logger("otter", LOGDIR) disable_btn = gr.Button.update(interactive=False) def regenerate(dialog_state, requ...
null
7,872
import os import datetime import json import base64 from PIL import Image import gradio as gr import hashlib import requests from utils import build_logger from conversation import model import io logger = build_logger("otter", LOGDIR) current_model = model disable_btn = gr.Button.update(interactive=False) def init_inp...
null
7,873
import os import datetime import json import base64 from PIL import Image import gradio as gr import hashlib import requests from utils import build_logger from conversation import model import io logger = build_logger("otter", LOGDIR) no_change_btn = gr.Button.update() disable_btn = gr.Button.update(interactive=False)...
null
7,874
import os import datetime import json import base64 from PIL import Image import gradio as gr import hashlib import requests from utils import build_logger from conversation import model import io logger = build_logger("otter", LOGDIR) no_change_btn = gr.Button.update() disable_btn = gr.Button.update(interactive=False)...
null
7,875
import os import datetime import json import base64 from PIL import Image import gradio as gr import hashlib import requests from utils import build_logger from conversation import model import io logger = build_logger("otter", LOGDIR) def encode_image(image: Image.Image, format: str = "PNG") -> str: with io.BytesI...
null
7,876
import os import datetime import json import base64 from PIL import Image import gradio as gr import hashlib import requests from utils import build_logger from conversation import model import io logger = build_logger("otter", LOGDIR) current_model = model def init_input_state(): return {"images": [], "text": "", ...
null
7,877
import logging import logging.handlers import os import sys import requests LOGDIR = "./logs" handler = None class StreamToLogger(object): def __init__(self, logger, log_level=logging.INFO): def __getattr__(self, attr): def write(self, buf): def flush(self): def build_logger(logger_name, logger_fil...
null
7,878
import logging import logging.handlers import os import sys import requests The provided code snippet includes necessary dependencies for implementing the `disable_torch_init` function. Write a Python function `def disable_torch_init()` to solve the following problem: Disable the redundant torch default initialization...
Disable the redundant torch default initialization to accelerate model creation.
7,879
import logging import logging.handlers import os import sys import requests def pretty_print_semaphore(semaphore): if semaphore is None: return "None" return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})"
null
7,880
import argparse import asyncio import json import time import threading import uuid from PIL import Image from io import BytesIO import base64 from fastapi import FastAPI, Request, BackgroundTasks from fastapi.responses import StreamingResponse import requests from transformers import TextIteratorStreamer import torch ...
null
7,881
import argparse import asyncio import json import time import threading import uuid from PIL import Image from io import BytesIO import base64 from fastapi import FastAPI, Request, BackgroundTasks from fastapi.responses import StreamingResponse import requests from transformers import TextIteratorStreamer import torch ...
null