id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
29,133
from acme import types import jax import numpy as np import reverb from reverb import item_selectors from reverb import rate_limiters from reverb import reverb_types import tensorflow as tf import tree The provided code snippet includes necessary dependencies for implementing the `replay_sample_to_sars_transition` fun...
Converts the replay sample to a types.Transition. NB: If is_sequence is True then the last next_observation of each sequence is rubbish. Don't train on it. Args: sample: The replay sample is_sequence: If False we expect the sample data to match the types.Transition already. Otherwise we expect a batch of sequences of s...
29,134
from acme import types import jax import numpy as np import reverb from reverb import item_selectors from reverb import rate_limiters from reverb import reverb_types import tensorflow as tf import tree The provided code snippet includes necessary dependencies for implementing the `transition_to_replaysample` function....
Converts a types.Transition to a reverb.ReplaySample.
29,135
import os import os.path import shutil import time from typing import Optional, Tuple from absl import flags def get_unique_id() -> Tuple[str, ...]: """Makes a unique identifier for this process; override with --acme_id.""" # By default we'll use the global id. identifier = _DATETIME # If the --acme_id flag is ...
Process the path string. This will process the path string by running `os.path.expanduser` to replace any initial "~". It will also append a unique string on the end of the path and create the directories leading to this path if necessary. Args: path: string defining the path to process and create. *subpaths: potential...
29,136
import os import os.path import shutil import time from typing import Optional, Tuple from absl import flags The provided code snippet includes necessary dependencies for implementing the `rmdir` function. Write a Python function `def rmdir(path: str)` to solve the following problem: Remove directory recursively. Her...
Remove directory recursively.
29,137
from typing import Optional from acme.utils import loggers def make_experiment_logger(label: str, steps_key: Optional[str] = None, task_instance: int = 0) -> loggers.Logger: del task_instance if steps_key is None: steps_key = f'{label}_steps' return logger...
null
29,138
import threading import time from typing import Dict, Mapping, Optional, Union from acme import core Number = Union[int, float] The provided code snippet includes necessary dependencies for implementing the `_prefix_keys` function. Write a Python function `def _prefix_keys(dictionary: Dict[str, Number], prefix: str)` ...
Return a dictionary with prefixed keys. Args: dictionary: dictionary to return a copy of. prefix: string to use as the prefix. Returns: Return a copy of the given dictionary whose keys are replaced by "{prefix}_{key}". If the prefix is the empty string it returns the given dictionary unchanged.
29,139
from typing import Sequence, List, TypeVar, Any import numpy as np import tree ElementType = TypeVar('ElementType') def fast_map_structure(func, *structure): """Faster map_structure implementation which skips some error checking.""" flat_structure = (tree.flatten(s) for s in structure) entries = zip(*flat_structu...
Stacks a list of identically nested objects. This takes a sequence of identically nested objects and returns a single nested object whose ith leaf is a stacked numpy array of the corresponding ith leaf from each element of the sequence. For example, if `sequence` is: ```python [{ 'action': np.array([1.0]), 'observation...
29,140
from typing import Sequence, List, TypeVar, Any import numpy as np import tree ElementType = TypeVar('ElementType') The provided code snippet includes necessary dependencies for implementing the `unstack_sequence_fields` function. Write a Python function `def unstack_sequence_fields(struct: ElementType, ...
Converts a struct of batched arrays to a list of structs. This is effectively the inverse of `stack_sequence_fields`. Args: struct: An (arbitrarily nested) structure of arrays. batch_size: The length of the leading dimension of each array in the struct. This is assumed to be static and known. Returns: A list of structs...
29,141
import contextlib import ctypes import threading from typing import Any, Callable, Optional import launchpad _Handler = Callable[[], Any] The provided code snippet includes necessary dependencies for implementing the `runtime_terminator` function. Write a Python function `def runtime_terminator(callback: Optional[_Han...
Runtime terminator used for stopping computation upon agent termination. Runtime terminator optionally executed a provided `callback` and then raises `SystemExit` exception in the thread performing the computation. Args: callback: callback to execute before raising exception. Yields: None.
29,142
import itertools import operator from typing import Any, Iterator, List, Sequence The provided code snippet includes necessary dependencies for implementing the `unzip_iterators` function. Write a Python function `def unzip_iterators(zipped_iterators: Iterator[Sequence[Any]], num_sub_iterators: int...
Returns unzipped iterators. Note that simply returning: [(x[i] for x in iter_tuple[i]) for i in range(num_sub_iterators)] seems to cause all iterators to point to the final value of i, thus causing all sub_learners to consume data from this final iterator. Args: zipped_iterators: zipped iterators (e.g., from zip_iterat...
29,143
import logging import time from typing import Any, Callable from acme.utils.loggers import base import numpy as np def _format_key(key: str) -> str: """Internal function for formatting keys.""" return key.replace('_', ' ').title() def _format_value(value: Any) -> str: """Internal function for formatting values.""...
Converts `values` to a pretty-printed string. This takes a dictionary `values` whose keys are strings and returns a formatted string such that each [key, value] pair is separated by ' = ' and each entry is separated by ' | '. The keys are sorted alphabetically to ensure a consistent order, and snake case is split into ...
29,144
import logging from typing import Any, Callable, Mapping, Optional from acme.utils.loggers import aggregators from acme.utils.loggers import asynchronous as async_logger from acme.utils.loggers import base from acme.utils.loggers import csv from acme.utils.loggers import filters from acme.utils.loggers import terminal ...
Makes a default Acme logger. Args: label: Name to give to the logger. save_data: Whether to persist data. time_delta: Time (in seconds) between logging events. asynchronous: Whether the write function should block or not. print_fn: How to print to terminal (defaults to print). serialize_fn: An optional function to appl...
29,145
import time from typing import Optional from absl import logging from acme.utils.loggers import base import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `_format_key` function. Write a Python function `def _format_key(key: str) -> str` to solve the following problem: ...
Internal function for formatting keys in Tensorboard format.
29,146
import atexit import functools import inspect import os import sys import time from typing import Any, Callable, Optional from absl import flags from absl import logging from acme.utils import counting from acme.utils import signals The provided code snippet includes necessary dependencies for implementing the `partia...
Return a partial function application by overriding default keywords. This function is equivalent to `functools.partial(function, **kwargs)` but will raise a `ValueError` when called if either the given keyword arguments are not defined by `function` or if they do not have defaults. This is useful as a way to define a ...
29,147
import atexit import functools import inspect import os import sys import time from typing import Any, Callable, Optional from absl import flags from absl import logging from acme.utils import counting from acme.utils import signals FLAGS = flags.FLAGS def is_local_run() -> bool: return FLAGS.lp_launch_type.startswi...
null
29,148
import atexit import functools import inspect import os import sys import time from typing import Any, Callable, Optional from absl import flags from absl import logging from acme.utils import counting from acme.utils import signals FLAGS = flags.FLAGS The provided code snippet includes necessary dependencies for impl...
Returns Docker XManager resources for each program's node. For each node of the Launchpad's program appropriate hardware requirements are specified (CPU, memory...), while the list of PyPi packages specified in the requirements file will be installed inside the Docker images. Args: program: program for which to constru...
29,149
from typing import Type, TypeVar T = TypeVar('T') def record_class_usage(cls: Type[T]) -> Type[T]: return cls
null
29,150
import os import typer from yaspin import yaspin from pathlib import Path from collections import Counter import fnmatch import re import shutil from config import INCLUDED_EXTENSIONS, EXTENSION_TO_LANGUAGE EXTENSION_TO_LANGUAGE = { 'py': 'Python', 'js': 'JavaScript', 'java': 'Java', 'rb': 'Ruby', ...
null
29,151
import os import typer from yaspin import yaspin from pathlib import Path from collections import Counter import fnmatch import re import shutil from config import INCLUDED_EXTENSIONS, EXTENSION_TO_LANGUAGE def llm_write_files(prompt,target_path,waiting_message,success_message,globals): file_content = "" ...
null
29,152
import os import typer from yaspin import yaspin from pathlib import Path from collections import Counter import fnmatch import re import shutil from config import INCLUDED_EXTENSIONS, EXTENSION_TO_LANGUAGE def load_templates_from_directory(directory_path): templates = {} for filename in os.listdir(directory_p...
null
29,153
import os import typer from yaspin import yaspin from pathlib import Path from collections import Counter import fnmatch import re import shutil from config import INCLUDED_EXTENSIONS, EXTENSION_TO_LANGUAGE def parse_code_string(code_string): sections = code_string.split('---') pattern = re.compile(r'^(.+...
null
29,154
import os import typer from yaspin import yaspin from pathlib import Path from collections import Counter import fnmatch import re import shutil from config import INCLUDED_EXTENSIONS, EXTENSION_TO_LANGUAGE def find_and_replace_file(filepath,find,replace): with open(filepath, 'r') as file: testfile_content...
null
29,155
import subprocess import typer from yaspin import yaspin from pathlib import Path from tree_sitter import Language, Parser, Node from collections.abc import Iterator from config import EXTENSION_TO_TREE_SITTER_GRAMMAR_REPO, EXTENSION_TO_LANGUAGE EXTENSION_TO_TREE_SITTER_GRAMMAR_REPO = { 'py': TREE_SITTER_REPO_STUB...
null
29,156
from utils import prompt_constructor, llm_write_file from config import HIERARCHY, GUIDELINES, WRITE_CODE, CREATE_DOCKER, SINGLEFILE def prompt_constructor(*args): prompt = "" for arg in args: with open(os.path.abspath(f'prompts/{arg}'), 'r') as file: prompt += file.read().strip() retur...
Create Dockerfile
29,157
from utils import prompt_constructor, llm_write_file, llm_run, build_directory_structure, copy_files, write_to_memory, read_from_memory, file_exists_in_memory, convert_sigs_to_string from config import HIERARCHY, GUIDELINES, WRITE_CODE, GET_EXTERNAL_DEPS, GET_INTERNAL_DEPS, ADD_DOCKER_REQUIREMENTS, REFINE_DOCKERFILE, W...
Get external and internal dependencies of source file
29,158
from utils import prompt_constructor, llm_write_file, llm_run, build_directory_structure, copy_files, write_to_memory, read_from_memory, file_exists_in_memory, convert_sigs_to_string from config import HIERARCHY, GUIDELINES, WRITE_CODE, GET_EXTERNAL_DEPS, GET_INTERNAL_DEPS, ADD_DOCKER_REQUIREMENTS, REFINE_DOCKERFILE, W...
Write migration file
29,159
from utils import prompt_constructor, llm_write_file, llm_run, build_directory_structure, copy_files, write_to_memory, read_from_memory, file_exists_in_memory, convert_sigs_to_string from config import HIERARCHY, GUIDELINES, WRITE_CODE, GET_EXTERNAL_DEPS, GET_INTERNAL_DEPS, ADD_DOCKER_REQUIREMENTS, REFINE_DOCKERFILE, W...
Copy all files recursively with included extensions from the source directory to the target directory in the same relative structure
29,160
from utils import prompt_constructor, llm_write_file, llm_run, build_directory_structure, construct_relevant_files from config import HIERARCHY, GUIDELINES, WRITE_CODE, IDENTIFY_ACTION, MOVE_FILES, CREATE_FILE, IDENTIFY_FILE, DEBUG_FILE, DEBUG_TESTFILE, HUMAN_INTERVENTION, SINGLEFILE, FILENAMES, MAX_ERROR_MESSAGE_CHARA...
null
29,161
from utils import prompt_constructor, llm_write_file, llm_run, build_directory_structure, construct_relevant_files from config import HIERARCHY, GUIDELINES, WRITE_CODE, IDENTIFY_ACTION, MOVE_FILES, CREATE_FILE, IDENTIFY_FILE, DEBUG_FILE, DEBUG_TESTFILE, HUMAN_INTERVENTION, SINGLEFILE, FILENAMES, MAX_ERROR_MESSAGE_CHARA...
null
29,162
from flask import Flask, request, jsonify from bcrypt import hashpw, gensalt from db import read_items, write_items def hello_world(): return "Hello World!"
null
29,163
from flask import Flask, request, jsonify from bcrypt import hashpw, gensalt from db import read_items, write_items def read_items(): with open('storage/items.json') as f: grocery_items = json.load(f) return grocery_items def get_grocery_items(): try: grocery_items = read_items() i...
null
29,164
from flask import Flask, request, jsonify from bcrypt import hashpw, gensalt from db import read_items, write_items def read_items(): with open('storage/items.json') as f: grocery_items = json.load(f) return grocery_items def write_items(grocery_items): with open('storage/items.json', 'w') as f: ...
null
29,165
from flask import Flask, request, jsonify from bcrypt import hashpw, gensalt from db import read_items, write_items def read_items(): with open('storage/items.json') as f: grocery_items = json.load(f) return grocery_items def write_items(grocery_items): with open('storage/items.json', 'w') as f: ...
null
29,166
from flask import Flask, request, jsonify from bcrypt import hashpw, gensalt from db import read_items, write_items def hash_password(password): try: return hashpw(password.encode('utf-8'), gensalt()).decode('utf-8') except Exception as e: return e, 500
null
29,172
import json def read_items(): with open('storage/items.json') as f: grocery_items = json.load(f) return grocery_items
null
29,173
import json def write_items(grocery_items): with open('storage/items.json', 'w') as f: json.dump(grocery_items, f)
null
29,176
from flask import Flask, request, jsonify from bcrypt import hashpw, gensalt from db import read_items, write_items def read_items(): def write_items(grocery_items): def add_grocery_item(): try: new_item = request.json print(new_item["id"],new_item,flush=True) grocery_items = read_items()...
null
29,177
from flask import Flask, request, jsonify from bcrypt import hashpw, gensalt from db import read_items, write_items def read_items(): def write_items(grocery_items): def delete_grocery_item(item_id): try: grocery_items = read_items() grocery_items = [item for item in grocery_items if item["id"] !...
null
29,182
from flask import Flask, request, jsonify from bcrypt import hashpw, gensalt from db import read_items, write_items def read_items(): def get_grocery_items(): try: grocery_items = read_items() items = [{"id": item["id"], "name": item["name"], "price": item["price"]} for item in grocery_items] ...
null
29,188
import sys import os import time import argparse import random import math import numpy as np import paddle from datasets import get_dataloader from datasets import get_dataset from config import get_config from config import update_config from utils import AverageMeter from utils import get_logger from utils import wr...
return argumeents, this will overwrite the config by (1) yaml file (2) argument values
29,189
import sys import os import time import argparse import random import math import numpy as np import paddle from datasets import get_dataloader from datasets import get_dataset from config import get_config from config import update_config from utils import AverageMeter from utils import get_logger from utils import wr...
main method for each process
29,190
import os import math from paddle.io import Dataset from paddle.io import DataLoader from paddle.io import DistributedBatchSampler from paddle.vision import transforms from paddle.vision import image_load from augment import auto_augment_policy_original from augment import AutoAugment from augment import rand_augment_p...
Get training transforms For training, a RandomResizedCrop is applied with random mirror, then normalization is applied with mean and std. The input pixel values must be rescaled to [0, 1.]. Outputs is converted to tensor. Args: config: configs contains IMAGE_SIZE, see config.py for details Returns: transforms_train: tr...
29,191
import os import math from paddle.io import Dataset from paddle.io import DataLoader from paddle.io import DistributedBatchSampler from paddle.vision import transforms from paddle.vision import image_load from augment import auto_augment_policy_original from augment import AutoAugment from augment import rand_augment_p...
Get dataset from config and mode (train/val) Returns the related dataset object according to configs and mode(train/val) Args: config: configs contains dataset related settings. see config.py for details is_train: bool, set True to use training set, otherwise val set. Default: True Returns: dataset: dataset object
29,192
import os from yacs.config import CfgNode as CN import yaml def _update_config_from_file(config, cfg_file): """Load cfg file (.yaml) and update config object Args: config: config object cfg_file: config file (.yaml) Return: None """ config.defrost() with open(cfg_file, 'r...
Update config by ArgumentParser Configs that are often used can be updated from arguments Args: args: ArgumentParser contains options Return: config: updated config
29,193
import os from yacs.config import CfgNode as CN import yaml _C = CN() _C.BASE = [''] _C.DATA = CN() _C.DATA.BATCH_SIZE = 256 _C.DATA.BATCH_SIZE_EVAL = None _C.DATA.DATA_PATH = '/dataset/imagenet/' _C.DATA.DATASET = 'imagenet2012' _C.DATA.IMAGE_SIZE = 224 _C.DATA.IMAGE_CHANNELS = 3 _C.DATA.CROP_PCT = 0.9 _C.DATA....
Return a clone of config and optionally overwrite it from yaml file
29,194
import paddle import paddle.nn as nn from droppath import DropPath The provided code snippet includes necessary dependencies for implementing the `windows_partition` function. Write a Python function `def windows_partition(x, window_size)` to solve the following problem: partite windows into window_size x window_size ...
partite windows into window_size x window_size Args: x: Tensor, shape=[b, h, w, c] window_size: int, window size Returns: x: Tensor, shape=[num_windows*b, window_size, window_size, c]
29,195
import paddle import paddle.nn as nn from droppath import DropPath The provided code snippet includes necessary dependencies for implementing the `windows_reverse` function. Write a Python function `def windows_reverse(windows, window_size, H, W)` to solve the following problem: Window reverse Args: windows: (n_window...
Window reverse Args: windows: (n_windows * B, window_size, window_size, C) window_size: (int) window size H: (int) height of image W: (int) width of image Returns: x: (B, H, W, C)
29,196
import paddle import paddle.nn as nn from droppath import DropPath class SwinTransformer(nn.Layer): """SwinTransformer class Attributes: num_classes: int, num of image classes num_stages: int, num of stages contains patch merging and Swin blocks depths: list of int, num of Swin blocks in...
build swin model from config
29,197
import os import numpy as np import paddle import torch import timm from swin import build_swin as build_model from config import get_config def print_model_named_params(model): print('----------------------------------') for name, param in model.named_parameters(): print(name, param.shape) print('...
null
29,198
import os import numpy as np import paddle import torch import timm from swin import build_swin as build_model from config import get_config def print_model_named_buffers(model): print('----------------------------------') for name, param in model.named_buffers(): print(name, param.shape) print('--...
null
29,199
import os import numpy as np import paddle import torch import timm from swin import build_swin as build_model from config import get_config def torch_to_paddle_mapping(model_name, config): mapping = [ ('patch_embed.proj', 'patch_embedding.patch_embed'), ('patch_embed.norm', 'patch_embedding.norm'),...
null
29,200
import numpy as np import paddle def rand_bbox(image_shape, lam, count=None): """ CutMix bbox by lam value Generate 1 random bbox by value lam. lam is the cut size rate. The cut_size is computed by sqrt(1-lam) * image_size. Args: image_shape: tuple/list, image height and width lam: float...
Generate bbox and apply correction for lambda If the mimmax is None, apply the standard cutmix by lam value, If the minmax is set, apply the cutmix by min and max percentage values. Args: image_shape: tuple/list, image height and width lam: float, cutmix lambda value minmax: tuple/list, min and max percentage values of...
29,201
import numpy as np import paddle def one_hot(x, num_classes, on_value=1., off_value=0.): """ Generate one-hot vector for label smoothing Args: x: tensor, contains label/class indices num_classes: int, num of classes (len of the one-hot vector) on_value: float, the vector value at label i...
mixup and label smoothing in batch label smoothing is firstly applied, then mixup is applied by mixing the bacth and its flip, with a mixup rate. Args: label: tensor, label tensor with shape [N], contains the class indices num_classes: int, num of all classes lam: float, mixup rate, default=1.0 smoothing: float, label ...
29,202
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps class SubPolicy: """Subpolicy Read augment name and magnitude, apply augment with probability Args: op_name: str, augment operation name prob: float, if prob > random prob, apply augment magnitude: int, in...
policy v0: hack from timm
29,203
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps class SubPolicy: """Subpolicy Read augment name and magnitude, apply augment with probability Args: op_name: str, augment operation name prob: float, if prob > random prob, apply augment magnitude: int, in...
policy v0r: hack from timm
29,204
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps class SubPolicy: """Subpolicy Read augment name and magnitude, apply augment with probability Args: op_name: str, augment operation name prob: float, if prob > random prob, apply augment magnitude: int, in...
policy originalr: hack from timm
29,205
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps LEVEL_DENOM = 10 def randomly_negate(value): """negate the value with 0.5 prob""" return -value if random.random() > 0.5 else value def shear_level_to_arg(level): # range [-0.3, 0.3] level = (level / LEVEL_DENOM) * 0.3 l...
null
29,206
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps LEVEL_DENOM = 10 def randomly_negate(value): def translate_absolute_level_to_arg(level): # translate const = 100 level = (level / LEVEL_DENOM) * 100. level = randomly_negate(level) return (level,)
null
29,207
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps LEVEL_DENOM = 10 def randomly_negate(value): def translate_relative_level_to_arg(level): # range [-0.45, 0.45] level = (level / LEVEL_DENOM) * 0.45 level = randomly_negate(level) return (level,)
null
29,208
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps LEVEL_DENOM = 10 def randomly_negate(value): """negate the value with 0.5 prob""" return -value if random.random() > 0.5 else value def rotate_level_to_arg(level): # range [-30, 30] level = (level / LEVEL_DENOM) * 30. le...
null
29,209
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps LEVEL_DENOM = 10 def solarize_level_to_arg(level): # range [0, 256] # intensity/severity of augmentation decreases with level return (int((level / LEVEL_DENOM) * 256),)
null
29,210
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps LEVEL_DENOM = 10 def solarize_increasing_level_to_arg(level): # range [0, 256] # intensity/severity of augmentation increases with level return (256 - int((level / LEVEL_DENOM) * 256),)
null
29,211
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps LEVEL_DENOM = 10 def solarize_add_level_to_arg(level): # range [0, 110] return (int((level / LEVEL_DENOM) * 110),)
null
29,212
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps LEVEL_DENOM = 10 def posterize_level_to_arg(level): # range [0, 4] # intensity/severity of augmentation decreases with level return (int((level / LEVEL_DENOM) * 4),)
null
29,213
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps LEVEL_DENOM = 10 def posterize_increasing_level_to_arg(level): # range [4, 0] # intensity/severity of augmentation increases with level return (4 - int((level / LEVEL_DENOM) * 4),)
null
29,214
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps LEVEL_DENOM = 10 def posterize_original_level_to_arg(level): # range [4, 8] # intensity/severity of augmentation decreases with level return (int((level / LEVEL_DENOM) * 4) + 4,)
null
29,215
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps LEVEL_DENOM = 10 def enhance_level_to_arg(level): # range [0.1, 1.9] return ((level / LEVEL_DENOM) * 1.8 + 0.1,)
null
29,216
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps LEVEL_DENOM = 10 def randomly_negate(value): """negate the value with 0.5 prob""" return -value if random.random() > 0.5 else value def enhance_increasing_level_to_arg(level): # range [0.1, 1.9] level = (level / LEVEL_DENOM)...
null
29,217
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def shear_x(image, factor, fillcolor=(128, 128, 128)): return image.transform(image.size, Image.AFFINE, (1, factor, 0, 0, 1, 0), fillcolor=fillcolor)
null
29,218
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def shear_y(image, factor, fillcolor=(128, 128, 128)): return image.transform(image.size, Image.AFFINE, (1, 0, 0, factor, 1, 0), fillcolor=fillcolor)
null
29,219
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def translate_x_absolute(image, pixels, fillcolor=(128, 128, 128)): return image.transform(image.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), fillcolor=fillcolor)
null
29,220
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def translate_y_absolute(image, pixels, fillcolor=(128, 128, 128)): return image.transform(image.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), fillcolor=fillcolor)
null
29,221
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def translate_x_relative(image, pct, fillcolor=(128, 128, 128)): pixels = pct * image.size[0] return image.transform(image.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), fillcolor=fillcolor)
null
29,222
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def translate_y_relative(image, pct, fillcolor=(128, 128, 128)): pixels = pct * image.size[0] return image.transform(image.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), fillcolor=fillcolor)
null
29,223
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def rotate(image, degrees): return image.rotate(degrees)
null
29,224
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def auto_contrast(image, magnitude=None): return ImageOps.autocontrast(image)
null
29,225
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def invert(image, magnitude=None): return ImageOps.invert(image)
null
29,226
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def equalize(image, magnitude=None): return ImageOps.equalize(image)
null
29,227
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def solarize(image, thresh): return ImageOps.solarize(image, thresh)
null
29,228
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def solarize_add(image, add, thresh=128): lut = [] for i in range(256): if i < thresh: lut.append(min(255, i + add)) else: lut.append(i) if image.mode in ("L", "RGB"): if image.mod...
null
29,229
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def posterize(image, bits_to_keep): if bits_to_keep >= 8: return image return ImageOps.posterize(image, bits_to_keep)
null
29,230
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def contrast(image, factor): return ImageEnhance.Contrast(image).enhance(factor)
null
29,231
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def color(image, factor): return ImageEnhance.Color(image).enhance(factor)
null
29,232
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def brightness(image, factor): return ImageEnhance.Brightness(image).enhance(factor)
null
29,233
import random import numpy as np from PIL import Image, ImageEnhance, ImageOps def sharpness(image, factor): return ImageEnhance.Sharpness(image).enhance(factor)
null
29,234
import random import math import paddle def _get_pixels(per_pixel, rand_color, patch_size, dtype="float32"): if per_pixel: return paddle.normal(shape=patch_size).astype(dtype) if rand_color: return paddle.normal(shape=(patch_size[0], 1, 1)).astype(dtype) return paddle.zeros((patch_size[0], ...
null
29,235
import logging import sys import os import paddle import paddle.distributed as dist The provided code snippet includes necessary dependencies for implementing the `get_logger` function. Write a Python function `def get_logger(file_path)` to solve the following problem: Set logging file and format, logs are written in ...
Set logging file and format, logs are written in 2 loggers, one local_logger records the information on its own gpu/process, one master_logger records the overall/average information over all gpus/processes. Args: file_path: str, folder path of the logger files to write Return: local_logger: python logger for each proc...
29,236
import logging import sys import os import paddle import paddle.distributed as dist The provided code snippet includes necessary dependencies for implementing the `write_log` function. Write a Python function `def write_log(local_logger, master_logger, msg_local, msg_master=None, level='info')` to solve the following ...
Write messages in loggers Args: local_logger: python logger, logs information on single gpu master_logger: python logger, logs information over all gpus msg_local: str, message to log on local_logger msg_master: str, message to log on master_logger, if None, use msg_local, default: None level: str, log level, in ['info...
29,237
import logging import sys import os import paddle import paddle.distributed as dist The provided code snippet includes necessary dependencies for implementing the `all_reduce_mean` function. Write a Python function `def all_reduce_mean(x)` to solve the following problem: perform all_reduce on Tensor for gathering resu...
perform all_reduce on Tensor for gathering results from multi-gpus
29,238
import logging import sys import os import paddle import paddle.distributed as dist The provided code snippet includes necessary dependencies for implementing the `skip_weight_decay_fn` function. Write a Python function `def skip_weight_decay_fn(model, skip_list=[], filter_bias_and_bn=True)` to solve the following pro...
Set params with no weight decay during the training For certain params, e.g., positional encoding in ViT, weight decay may not needed during the learning, this method is used to find these params. Args: model: nn.Layer, model skip_list: list, a list of params names which need to exclude from weight decay, default: [] f...
29,239
import sys import os import time import argparse import random import math import numpy as np import paddle from datasets import get_dataloader from datasets import get_dataset from config import get_config from config import update_config from utils import AverageMeter from utils import get_logger from utils import wr...
return argumeents, this will overwrite the config by (1) yaml file (2) argument values
29,240
import sys import os import time import argparse import random import math import numpy as np import paddle from datasets import get_dataloader from datasets import get_dataset from config import get_config from config import update_config from utils import AverageMeter from utils import get_logger from utils import wr...
main method for each process
29,241
import os import math from paddle.io import Dataset from paddle.io import DataLoader from paddle.io import DistributedBatchSampler from paddle.vision import transforms from paddle.vision import image_load from augment import auto_augment_policy_original from augment import AutoAugment from augment import rand_augment_p...
Get training transforms For training, a RandomResizedCrop is applied with random mirror, then normalization is applied with mean and std. The input pixel values must be rescaled to [0, 1.]. Outputs is converted to tensor. Args: config: configs contains IMAGE_SIZE, see config.py for details Returns: transforms_train: tr...
29,242
import os import math from paddle.io import Dataset from paddle.io import DataLoader from paddle.io import DistributedBatchSampler from paddle.vision import transforms from paddle.vision import image_load from augment import auto_augment_policy_original from augment import AutoAugment from augment import rand_augment_p...
Get dataset from config and mode (train/val) Returns the related dataset object according to configs and mode(train/val) Args: config: configs contains dataset related settings. see config.py for details is_train: bool, set True to use training set, otherwise val set. Default: True Returns: dataset: dataset object
29,243
import os import math from paddle.io import Dataset from paddle.io import DataLoader from paddle.io import DistributedBatchSampler from paddle.vision import transforms from paddle.vision import image_load from augment import auto_augment_policy_original from augment import AutoAugment from augment import rand_augment_p...
Get dataloader from dataset, allows multiGPU settings. Multi-GPU loader is implements as distributedBatchSampler. Args: config: see config.py for details dataset: paddle.io.dataset object is_train: bool, when False, shuffle is off and BATCH_SIZE_EVAL is used, default: True use_dist_sampler: if True, DistributedBatchSam...
29,245
import os from yacs.config import CfgNode as CN import yaml _C = CN() _C.BASE = [''] _C.DATA = CN() _C.DATA.BATCH_SIZE = 256 _C.DATA.BATCH_SIZE_EVAL = None _C.DATA.DATA_PATH = '/dataset/imagenet/' _C.DATA.DATASET = 'imagenet2012' _C.DATA.IMAGE_SIZE = 224 _C.DATA.IMAGE_CHANNELS = 3 _C.DATA.CROP_PCT = 0.875 _C.DAT...
Return a clone of config and optionally overwrite it from yaml file
29,246
import os import numpy as np import paddle import torch import timm from coat import build_coat as build_model from config import get_config def print_model_named_params(model): print('----------------------------------') for name, param in model.named_parameters(): print(name, param.shape) print('...
null
29,247
import os import numpy as np import paddle import torch import timm from coat import build_coat as build_model from config import get_config def print_model_named_buffers(model): print('----------------------------------') for name, param in model.named_buffers(): print(name, param.shape) print('--...
null
29,248
import os import numpy as np import paddle import torch import timm from coat import build_coat as build_model from config import get_config def torch_to_paddle_mapping(model_name, config): mapping = [] for idx in range(4): layer_mapping = [ (f'cls_token{idx+1}', f'cls_tokens.{idx}'), ...
null
29,251
import paddle import paddle.nn as nn import paddle.nn.functional as F from droppath import DropPath class CoaT(nn.Layer): def __init__(self, image_size, patch_size, in_channels=3, num_classes=1000, embed_dims=(0, 0, 0, 0), ...
null