id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
0
from setuptools import find_packages, setup import os import subprocess import time def readme(): with open('README.md', encoding='utf-8') as f: content = f.read() return content
null
1
from setuptools import find_packages, setup import os import subprocess import time version_file = 'realesrgan/version.py' def get_hash(): if os.path.exists('.git'): sha = get_git_hash()[:7] else: sha = 'unknown' return sha def write_version_py(): content = """# GENERATED VERSION FILE #...
null
2
from setuptools import find_packages, setup import os import subprocess import time version_file = 'realesrgan/version.py' def get_version(): with open(version_file, 'r') as f: exec(compile(f.read(), version_file, 'exec')) return locals()['__version__']
null
3
from setuptools import find_packages, setup import os import subprocess import time def get_requirements(filename='requirements.txt'): here = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(here, filename), 'r') as f: requires = [line.replace('\n', '') for line in f.readlines()] ...
null
4
import argparse import cv2 import glob import mimetypes import numpy as np import os import shutil import subprocess import torch from basicsr.archs.rrdbnet_arch import RRDBNet from basicsr.utils.download_util import load_file_from_url from os import path as osp from tqdm import tqdm from realesrgan import RealESRGANer...
null
5
import argparse import cv2 import glob import mimetypes import numpy as np import os import shutil import subprocess import torch from basicsr.archs.rrdbnet_arch import RRDBNet from basicsr.utils.download_util import load_file_from_url from os import path as osp from tqdm import tqdm from realesrgan import RealESRGANer...
null
6
import os os.system('pip install gfpgan') os.system('python setup.py develop') import cv2 import shutil import tempfile import torch from basicsr.archs.rrdbnet_arch import RRDBNet from basicsr.archs.srvgg_arch import SRVGGNetCompact from realesrgan.utils import RealESRGANer def clean_folder(folder): for filename i...
null
7
import argparse import cv2 import numpy as np import os import sys from basicsr.utils import scandir from multiprocessing import Pool from os import path as osp from tqdm import tqdm def worker(path, opt): """Worker for each process. Args: path (str): Image path. opt (dict): Configuration dict. ...
Crop images to subimages. Args: opt (dict): Configuration dict. It contains: input_folder (str): Path to the input folder. save_folder (str): Path to save folder. n_thread (int): Thread number.
8
import cv2 import numpy as np from PIL import Image def rotate_array(image: np.ndarray, angle: float) -> np.ndarray: if angle == 0: return image h, w = image.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, angle, 1.0) return cv2.warpAffine(image, M, (w, h)) def rotat...
null
9
import traceback from typing import Dict from scripts.io.util import load_classes_from_directory from scripts.use_cases.face_detector import FaceDetector from scripts.use_cases.face_processor import FaceProcessor from scripts.use_cases.mask_generator import MaskGenerator def create(all_classes, type: str) -> Dict: ...
null
10
import traceback from typing import Dict from scripts.io.util import load_classes_from_directory from scripts.use_cases.face_detector import FaceDetector from scripts.use_cases.face_processor import FaceProcessor from scripts.use_cases.mask_generator import MaskGenerator def create(all_classes, type: str) -> Dict: def...
null
11
import traceback from typing import Dict from scripts.io.util import load_classes_from_directory from scripts.use_cases.face_detector import FaceDetector from scripts.use_cases.face_processor import FaceProcessor from scripts.use_cases.mask_generator import MaskGenerator def create(all_classes, type: str) -> Dict: ...
null
12
import operator from typing import Dict from lark import Lark, Tree def starts_with(a, b): return a.startswith(b)
null
13
import operator from typing import Dict from lark import Lark, Tree def ends_with(a, b): return a.endswith(b)
null
14
import operator from typing import Dict from lark import Lark, Tree def contains(a, b): return b in a
null
15
import operator from typing import Dict from lark import Lark, Tree def not_contains(a, b): return b not in a
null
16
import operator from typing import Dict from lark import Lark, Tree def evaluate(query: str, attributes: Dict[str, str]) -> bool: def validate(query: str): return evaluate(query, {})
null
17
from typing import Dict, List, Optional, Union from pydantic import BaseModel, root_validator, validator class Worker(BaseModel): name: str params: Optional[Dict] def default_params(cls, values): if "params" not in values or values["params"] is None: values["params"] = {} return ...
null
18
import os import gradio as gr from modules import script_callbacks, shared from scripts.entities.option import Option from scripts.io.util import inferencers_dir from scripts.ui import workflow_editor from scripts.ui.param_value_parser import ParamValueParser inferencers_dir = os.path.join(get_path("scripts", "inferen...
null
19
import json import os from typing import Any, Dict, List import gradio as gr from modules import shared from pydantic import ValidationError from scripts.io.util import workflows_dir from scripts.use_cases.workflow_manager import WorkflowManager def load_workflow(file: str) -> str: if file is not None: file...
null
20
import cv2 import numpy as np from modules.processing import StableDiffusionProcessingImg2Img from PIL import Image from scripts.entities.face import Face from scripts.use_cases.face_processor import FaceProcessor def color_generator(colors): while True: for color in colors: yield color
null
21
import importlib.util import inspect import os from typing import List, Type import modules.scripts as scripts from modules import shared def get_path(*p: str) -> str: dir = os.path.join(scripts.basedir(), *p) if not os.path.isdir(dir): dir = os.path.join(scripts.basedir(), "extensions", "sd-face-edito...
null
22
import seqio import t5.data from t5.data.glue_utils import get_glue_weight_mapping from t5.data.glue_utils import get_super_glue_weight_mapping from t5.data.glue_utils import get_super_glue_weight_mapping_sentinel import t5.data.tasks _GLUE_WEIGHT_MAPPING = get_glue_weight_mapping() _SUPER_GLUE_WEIGHT_MAPPING = get_su...
null
23
import seqio import t5.data from t5.data.glue_utils import get_glue_weight_mapping from t5.data.glue_utils import get_super_glue_weight_mapping from t5.data.glue_utils import get_super_glue_weight_mapping_sentinel import t5.data.tasks _GLUE_WEIGHT_MAPPING = get_glue_weight_mapping() _SUPER_GLUE_WEIGHT_MAPPING = get_su...
null
24
import gin import seqio DEFAULT_SPM_PATH = "gs://t5-data/vocabs/cc_all.32000/sentencepiece.model" DEFAULT_EXTRA_IDS = 100 def get_default_vocabulary(): return seqio.SentencePieceVocabulary(DEFAULT_SPM_PATH, DEFAULT_EXTRA_IDS)
null
25
import gin import seqio The provided code snippet includes necessary dependencies for implementing the `rate_num_examples` function. Write a Python function `def rate_num_examples( task, maximum=None, temperature=1.0, scale=1.0, fallback_to_num_input_examples=True)` to solve the following problem: Mixing rate ...
Mixing rate equal to the number of examples for the task.
26
import gin import seqio The provided code snippet includes necessary dependencies for implementing the `rate_unsupervised` function. Write a Python function `def rate_unsupervised(task, value=1e6)` to solve the following problem: Gin-configurable mixing rate for the unsupervised co-training task. Here is the function...
Gin-configurable mixing rate for the unsupervised co-training task.
27
import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing the `lower_text` function. Write a Python function `def lower_text(string, **unused_kwargs)` to solve the following problem: Lowercases text. Here is the function: def lower_text(string, **unused_kwargs): "...
Lowercases text.
28
import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing the `qa` function. Write a Python function `def qa(answer, example=None, is_target=False)` to solve the following problem: Returns answer, or all answers if the full example is provided. Here is the function: ...
Returns answer, or all answers if the full example is provided.
29
import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing the `span_qa` function. Write a Python function `def span_qa(answer, example=None, is_target=False)` to solve the following problem: Returns answer, or a dict with answers and context if the example is provided...
Returns answer, or a dict with answers and context if the example is provided.
30
import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing the `wsc_simple` function. Write a Python function `def wsc_simple(prediction, example=None, is_target=False)` to solve the following problem: Sees whether we predicted the referent or not. Here is the functio...
Sees whether we predicted the referent or not.
31
import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing the `rank_classification` function. Write a Python function `def rank_classification(score, example=None, is_target=False, passthrough_fea...
A postprocessor for the `rank_classification` preprocessor and metric.
32
import collections import functools from t5.data import postprocessors from t5.data import preprocessors from t5.evaluation import metrics GLUE_WEIGHT_MAPPING = { "glue_cola_v002": 8_551., "glue_sst2_v002": 67_349., "glue_mrpc_v002": 3_668., "glue_qqp_v002": 363_849., "glue_stsb_v002": 5_749., "...
null
33
import collections import functools from t5.data import postprocessors from t5.data import preprocessors from t5.evaluation import metrics SUPER_GLUE_WEIGHT_MAPPING = { "dpr_v001_simple": 1_322., "super_glue_wsc_v102_simple_train": 259., "super_glue_wsc_v102_simple_eval": 0., "super_glue_boolq_v102": 9_...
null
34
import collections import functools from t5.data import postprocessors from t5.data import preprocessors from t5.evaluation import metrics SUPER_GLUE_WEIGHT_MAPPING_SENTINEL = { "dpr_v001_simple_1_sentinel": 1_322., "super_glue_wsc_v102_simple_1_sentinel_train": 259., "super_glue_wsc_v102_simple_1_sentinel_...
null
35
import collections import functools from t5.data import postprocessors from t5.data import preprocessors from t5.evaluation import metrics The provided code snippet includes necessary dependencies for implementing the `get_glue_text_preprocessor` function. Write a Python function `def get_glue_text_preprocessor(builde...
Return the glue preprocessor. Args: builder_config: a BuilderConfig Returns: a preprocessor function
36
import collections import functools from t5.data import postprocessors from t5.data import preprocessors from t5.evaluation import metrics def get_glue_postprocess_fn(builder_config): if builder_config.name == "stsb": return postprocessors.string_to_float elif builder_config.name == "multirc": return postp...
null
37
import collections import functools from t5.data import postprocessors from t5.data import preprocessors from t5.evaluation import metrics GLUE_METRICS = collections.OrderedDict([ ("cola", [metrics.sklearn_metrics_wrapper( "matthews_corrcoef", metric_post_process_fn=lambda x: 100 * x)]), ("sst2", [metri...
null
38
import collections import functools from t5.data import postprocessors from t5.data import preprocessors from t5.evaluation import metrics SUPERGLUE_METRICS = collections.OrderedDict([ ("boolq", [metrics.accuracy]), ("cb", [metrics.mean_multiclass_f1(num_classes=3), metrics.accuracy]), ("copa", [metrics.acc...
null
39
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Convert a summarization dataset to a text2text pair. For example, say the dataset returns examples of this format: {'article': <article>, 'highlights': <summary>} If article_key = 'article', summary_key = 'highlights', then the outputs will have the format: {'inputs': 'summarize': <article>, 'targets': <summary>} Args:...
40
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf NON_SPACED_LANGUAGE_RANGES = ( '\u1000-\u104f', # Burmese '\u4e00-...
Pad non-spaced languages with spaces around each character. Args: x: an example to process. text_key: a string, the key for the text feature to preprocess in the dataset examples. Returns: A preprocessed example.
41
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf AUTOTUNE = tf.data.experimental.AUTOTUNE def _pad_punctuation(text): """A...
Convert a TriviaQA example to multiple flattened examples. TriviaQA produces examples with this form: {'entity_pages': {dict of wiki entities}, 'search_results': <dict of web search results>, 'answer': {dict of all answers}, 'question': <question>, 'question_id': <question_id>, 'question_source': <question_source>} Thi...
42
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf AUTOTUNE = tf.data.experimental.AUTOTUNE def squad(x, include_context=True)...
Convert SQuAD examples to a text2text pair with span output. SQuAD produces examples with this form: {'context': <article>, 'question': <question>, 'answers': { 'text': [<all answers>] }} This function returns examples with the format {'inputs': 'context: <article> question: <question>', 'targets': 'start: <start_index...
43
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Randomly split single-string examples into multiple examples each. Segment lengths are chosen according to a log-uniform distribution. Each incoming string is chopped into multiple equal-length examples with the last one possibly being shorter. If the input string is longer than max_words_total, then we use one random ...
44
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def split_text_to_words(dataset, text_key='text', min_num_words=2): """Sp...
Create a dataset consisting of fill-in-the-blank text examples. The input examples should have a key text_key associated with a tf.string value. The output examples have keys 'inputs' and 'targets'. The input string is split on whitespace to form a sequence of words. This sequence is chopped randomly into segments of o...
45
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def split_text_to_words(dataset, text_key='text', min_num_words=2): """Sp...
Fill in the blank preprocessor that labels blank with a binned size. The actual blank size is sampled uniformly from the inclusive range of the min and max bin. The blank is then filled in with the closest bin size to the actual blank size. Args: dataset: a tf.data.Dataset, the dataset to preprocess. size_bins: a list,...
46
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf AUTOTUNE = tf.data.experimental.AUTOTUNE def translate(x, source_language, ...
Convert a multi-translate dataset to a text2text pair. For example, say the dataset returns examples which have a 'translations' feature key so that examples have the following format: { ... 'translations': { 'language': ['de', 'fr', 'en'], 'translation': ['Das ist gut.', 'Ca c'est bon', 'That is good.'] }, ... } If so...
47
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Converts DPR examples to a simple text to text format. A typical example from the definite pronoun resolution dataset might look like { 'sentence': 'Bob asked Tom if he can lend some money.', 'pronoun': 'he', 'candidates': ['Bob', 'Tom'], 'label': 1, } This will be transformed to { 'inputs': 'wsc: Bob asked Tom if *he*...
48
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def neighboring_pairs(dataset, text_key='text', reuse_sentences=True): ""...
Create a dataset containing a next sentence prediction objective. The input examples should have a key text_key associated with a tf.string value. The output examples have keys 'inputs' and 'targets'. EXAMPLE OUTPUTS: { input: "nsp: sentence1: The man went to the store. sentence2: Penguins are " "flightless birds.", ta...
49
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Basic language modeling objective for text - empty inputs. Given inputs with the format: {"text": "Here is some text."} This preprocess produces examples with the format {"inputs": "", "targets": "Here is some text."} Args: x: an example to process. Returns: A preprocessed example.
50
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf AUTOTUNE = tf.data.experimental.AUTOTUNE def _wsc_inputs(x): """Given an ...
Converts SuperGLUE WSC examples to a simple text to text format. A typical example from SuperGLUE WSC might look like { 'text': 'Mitchell asked Tom if he could lend some money.', 'span1_text': 'Tom', 'span2_text': 'he', 'span2_index': 4, } This will be transformed to { 'inputs': 'wsc: Bob asked Tom if *he* can lend som...
51
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Converts GLUE WNLI examples to a simple text to text format. A typical example from WNLI might look like: { 'sentence1': 'The fish ate the worm. It was tasty.', 'sentence2': 'The worm was tasty.', 'label': 1, } This will be transformed to: { 'inputs': 'wsc: The fish ate the worm. *It* was tasty.', 'targets': 'The worm'...
52
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def rank_classification( ds: tf.data.Dataset, inputs_fn: Callable[[...
Create 'inputs' and 'targets' strings for ranking classification. Intended to be used with `rank_classification` postprocessor and metric. Inputs will be formatted by filling in the feature values in the `inputs_formats` and `targets_formats` strings. Nested features can be accessed by concatenating the features using ...
53
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Splits TSV lines into dict examples mapping field name to string value. Args: line: an example containing a comma/tab-delimited string. field_names: a list of strings, the ordered names of the TSV fields. Defaults to "inputs" and "targets". field_delim: a string, the delimiter to split on e.g. ',' for csv. field_column...
54
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
r"""Parse tab-delimited strings into inputs and targets. This function takes a tf.data.Dataset of strings, each of which contains tab-delimited fields. The function returns a tf.data.Dataset of feature dictionaries of the form {"inputs": string, "targets": string}. inputs_format contains a template string and field num...
55
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def select_random_chunk(dataset: tf.data.Dataset, o...
Final pretraining objective used in Raffel et al., 2019. Args: dataset: A tf.data.Dataset with dictionaries containing the key `input_feature_key`. sequence_length: dict mapping of feature key to int length for that feature. output_features: mapping of keys to features. mean_noise_span_length: the mean number of tokens...
56
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def select_random_chunk(dataset: tf.data.Dataset, o...
Baseline pretraining objective used in Raffel et al., 2019.
57
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def select_random_chunk(dataset: tf.data.Dataset, o...
Prefix language modeling objective used in Raffel et al. 2019.
58
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def select_random_chunk(dataset: tf.data.Dataset, o...
Full language modeling objective with EOS only at document boundaries.
59
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Token-preprocessor to trim sequence at the beginning. Args: x: an example with dictionaries containing keys_to_trim. sequence_length: a dict of ints. keys_to_trim: a list of feature keys. Returns: A preprocessed example.
60
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Token preprocessor for the trivia QA dataset to truncate inputs. This function takes a dataset containing "targets" and "inputs". It searches for the "targets" in the "inputs" and truncates the "inputs" to `sequence_length` while ensuring that the "targets" are present in the "inputs". The function will randomly select...
61
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Configure this to point at unsupervised preprocessors. This function creates an extra level of indirection in case we want different unsupervised pretraining functions in the future which do not fit into the denoise() framework. This function should be used as a post-cache preprocessing function. Args: dataset: A tf.da...
62
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def split_tokens(dataset: tf.data.Dataset, min_tokens_per_...
null
63
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def split_tokens(dataset: tf.data.Dataset, min_tokens_per_...
null
64
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Concatenate tokens across examples, then split to fixed-size chunks. Chunk length is determined by sequence_length[feature_key]. Args: dataset: a tf.data.Dataset sequence_length: a dict of ints. output_features: a dict mapping feature name to t5.data.Feature. feature_key: a string Returns: a tf.data.Dataset
65
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Filter examples by string length. Args: dataset: a tf.data.Dataset (not tokenized) feature_key: a string min_length: an integer max_length: an integer Returns: a tf.data.Dataset
66
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def random_spans_helper(inputs_length=gin.REQUIRED, ...
Helper for gin-configuring split_tokens with random_spans_noise_mask.
67
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def random_spans_helper(inputs_length=gin.REQUIRED, ...
Helper for gin-configuring the targets sequence length.
68
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Noise mask consisting of equally spaced spans of equal length. The span length and the offset are chosen randomly per-example. The beginning and end of the sequence may be part of shorter spans of noise. For example, if noise_density=0.25 and a span length of 2 is chosen, then the output might be: [T F F F F F F T T F ...
69
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def noise_span_to_sentinel(tokens, noise_mask, vocabulary, seeds): """Rep...
null
70
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Permute the noise tokens, keeping the non-noise tokens where they are. Args: tokens: a 1d integer Tensor noise_mask: a boolean Tensor with the same shape as tokens vocabulary: an unused vocabulary.Vocabulary seeds: an int32 Tensor, sized (1, 2) Returns: a Tensor with the same shape and dtype as tokens
71
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Replace each noise token with a random token from the sequence. Args: tokens: a 1d integer Tensor noise_mask: a boolean Tensor with the same shape as tokens vocabulary: an unused vocabulary.Vocabulary seeds: an int32 Tensor, sized (1, 2) Returns: a Tensor with the same shape and dtype as tokens
72
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def noise_token_to_sentinel(tokens, noise_mask, vocabulary, seeds): """Re...
Replace each noise token with a random token or a sentinel. For each masked token, with probability random_prob, we replace it by a random token from the vocabulary. Otherwise, we replace it with a sentinel. Args: tokens: a 1d integer Tensor noise_mask: a boolean Tensor with the same shape as tokens vocabulary: a vocab...
73
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf def select_random_chunk(dataset: tf.data.Dataset, o...
Prepares targets to be used for prefix LM objective.
74
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Pack two examples into one with the prefix LM objective.
75
import collections import functools import math import re from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, Union import uuid from absl import logging import babel import gin import seqio import tensorflow.compat.v2 as tf The provided code snippet includes necessary dependencies for implementing...
Randomly split the tokens for the prefix LM objective.
76
import collections import os from absl import logging import numpy as np import pandas as pd import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds Event = collections.namedtuple("event", ["step", "value"]) The provided code snippet includes necessary dependencies for implementing the `parse_events_files...
Parse all TensorBoard events files in tb_summary_dir. Args: tb_summary_dir: str, path to look for events files in. seqio_summaries: boolean, whether event summaries are generated by SeqIO Evaluator. Returns: A dict, where each key is a TensorBoard tag and each value is a list of Event tuples with step and value attribu...
77
import collections import os from absl import logging import numpy as np import pandas as pd import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds The provided code snippet includes necessary dependencies for implementing the `get_eval_metric_values` function. Write a Python function `def get_eval_metri...
Filter TensorBoard events to only include those for eval metrics. Args: events: dict of list of (step, value) tuples where keys are tags. task_name: string, if not provided, then the function will look for the task name in the events tags. Returns: Dict where key is task_name/metric_name and value is (step, value) tupl...
78
import collections import os from absl import logging import numpy as np import pandas as pd import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds METRIC_NAMES = collections.OrderedDict([ ("glue_average", Metric("Average GLUE Score")), ("glue_cola_v002/matthews_corrcoef", Metric("CoLA")), ("g...
null
79
import collections import os from absl import logging import numpy as np import pandas as pd import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds METRIC_NAMES = collections.OrderedDict([ ("glue_average", Metric("Average GLUE Score")), ("glue_cola_v002/matthews_corrcoef", Metric("CoLA")), ("g...
Compute average GLUE and SuperGLUE scores from a DataFrame. Will only compute a given average score if all of the metrics for that benchmark appear as columns in the DataFrame. Args: df: pandas.DataFrame, columns should be metric names. metric_names: dict mapping tensorboard tag to metric name. Returns: A pandas.DataFr...
80
import collections import os from absl import logging import numpy as np import pandas as pd import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds class Metric(object): def __init__(self, name, group=None): self.name = name self.group = group or name METRIC_NAMES = collections.OrderedDict([ ...
Convert `scores` into a pandas DataFrame.
81
import collections import os from absl import logging import numpy as np import pandas as pd import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds def metric_group_max(df, metric_names=None): """Find the step which achieves the highest mean value for a group of metrics.""" # Use METRIC_NAMES defined ...
Log scores to be copy/pasted into a spreadsheet.
82
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Computes BLEU score. Args: targets: list of strings or list of list of strings if multiple references are present. predictions: list of strings tokenizer: tokenizer option for corpus_bleu Returns: bleu_score across all targets and predictions
83
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Computes rouge score nondeterministically using the bootstrap. Args: targets: list of strings. predictions: list of strings. score_keys: list of strings with the keys to compute. verbose: whether to enable additional logging. **kwargs: additional keyword arguments for RougeScorer. Returns: dict with score_key: rouge sc...
84
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Computes rouge score deterministically (no bootstrap). Args: targets: list of strings predictions: list of strings score_keys: list of strings with the keys to compute **kwargs: additional keyword arguments for RougeScorer. Returns: dict with score_key: rouge score across all targets and predictions
85
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Computes SQuAD metrics for span prediction tasks. Uses qa metric function to compute EM and F1 score. Args: targets: list of dict of answers (list of strings) and context (string) predictions: list of strings, each string is contains the space tokenized ids in the format: "start: 3 end: 6" Returns: dict with score_key:...
86
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Computes TriviaQA metrics, maximizing over answers per question. Args: targets: list of lists of strings predictions: list of strings Returns: dict with score_key: squad score across all targets and predictions
87
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
null
88
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Computes per-sequence accuracy. For each example, returns 1.0 if the target sequence EXACTLY matches the predicted sequence. Else, 0.0. Args: targets: list of strings predictions: list of strings Returns: float. Average sequence-level accuracy.
89
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Pearson correlation coefficient.
90
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Spearman correlation coefficient.
91
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Computes whether all targets match all predictions exactly.
92
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Returns a metric that only considers one example per group. Useful for things like ReCoRD where inputs may be replicated during training to handle multiple labels, but where at eval we only want a single copy of each example. Args: metric_fn: function, the metric to compute on the unique examples. group_key: the key fo...
93
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Returns a metric that averages `metric_fn` on sub-groups of results. The sub-groups are defined by aggregating results (targets and predictions) by accessing the feature specified by `group_key` in the target dicts. **WARNING**: Using this function can produce unreliable results if you do not pass in full groups. For e...
94
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Special metric for MultiRC which computes F1 score over all examples. This is necessary because the targets/predictions for MultiRC are dicts and the f1_score_with_invalid expects a list of True/False labels, not dicts. As a result we just need to key in the "value" for each of the example dicts before feeding into f1_...
95
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Compute Area Under the ROC and PR curves. ROC - Receiver Operating Characteristic PR - Precision and Recall Args: targets: np.ndarray of targets, either 0 or 1, or continuous values. scores: np.ndarray of scores, any value. targets_threshold: float, if target values are continuous values, this threshold binarizes them....
96
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Computes standard metrics classification based on log likelihood ranking. This metric is intended to be used along with the `rank_classification` preprocessor and postprocessor. Each example is scored (by log likelihood) for every possible label, and the label with the best score is selected as the prediction. In the c...
97
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Return mean sequence F1 score over all QA turns.
98
import collections import itertools import re import string from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from absl import logging import editdistance import flax import jax.numpy as jnp import numpy as np import sacrebleu import scipy.stats import seqio import sklearn.metrics from t5.evaluati...
Word-level edit distance between targets and predictions.
99
import os import re from absl import app from absl import flags from absl import logging import numpy as np import tensorflow.compat.v1 as tf def average_tensors(tensors): result = tensors[0] for t in tensors[1:]: result += t return result / len(tensors)
null