code
stringlengths
17
6.64M
def brightness(img, factor, **__): return ImageEnhance.Brightness(img).enhance(factor)
def sharpness(img, factor, **__): return ImageEnhance.Sharpness(img).enhance(factor)
def _randomly_negate(v): 'With 50% prob, negate the value' return ((- v) if (random.random() > 0.5) else v)
def _rotate_level_to_arg(level, _hparams): level = ((level / _MAX_LEVEL) * 30.0) level = _randomly_negate(level) return (level,)
def _enhance_level_to_arg(level, _hparams): return ((((level / _MAX_LEVEL) * 1.8) + 0.1),)
def _enhance_increasing_level_to_arg(level, _hparams): level = ((level / _MAX_LEVEL) * 0.9) level = (1.0 + _randomly_negate(level)) return (level,)
def _shear_level_to_arg(level, _hparams): level = ((level / _MAX_LEVEL) * 0.3) level = _randomly_negate(level) return (level,)
def _translate_abs_level_to_arg(level, hparams): translate_const = hparams['translate_const'] level = ((level / _MAX_LEVEL) * float(translate_const)) level = _randomly_negate(level) return (level,)
def _translate_rel_level_to_arg(level, hparams): translate_pct = hparams.get('translate_pct', 0.45) level = ((level / _MAX_LEVEL) * translate_pct) level = _randomly_negate(level) return (level,)
def _posterize_level_to_arg(level, _hparams): return (int(((level / _MAX_LEVEL) * 4)),)
def _posterize_increasing_level_to_arg(level, hparams): return ((4 - _posterize_level_to_arg(level, hparams)[0]),)
def _posterize_original_level_to_arg(level, _hparams): return ((int(((level / _MAX_LEVEL) * 4)) + 4),)
def _solarize_level_to_arg(level, _hparams): return (int(((level / _MAX_LEVEL) * 256)),)
def _solarize_increasing_level_to_arg(level, _hparams): return ((256 - _solarize_level_to_arg(level, _hparams)[0]),)
def _solarize_add_level_to_arg(level, _hparams): return (int(((level / _MAX_LEVEL) * 110)),)
class AugmentOp(): '\n Apply for video.\n ' def __init__(self, name, prob=0.5, magnitude=10, hparams=None): hparams = (hparams or _HPARAMS_DEFAULT) self.aug_fn = NAME_TO_OP[name] self.level_fn = LEVEL_TO_ARG[name] self.prob = prob self.magnitude = magnitude ...
def _select_rand_weights(weight_idx=0, transforms=None): transforms = (transforms or _RAND_TRANSFORMS) assert (weight_idx == 0) rand_weights = _RAND_CHOICE_WEIGHTS_0 probs = [rand_weights[k] for k in transforms] probs /= np.sum(probs) return probs
def rand_augment_ops(magnitude=10, hparams=None, transforms=None): hparams = (hparams or _HPARAMS_DEFAULT) transforms = (transforms or _RAND_TRANSFORMS) return [AugmentOp(name, prob=0.5, magnitude=magnitude, hparams=hparams) for name in transforms]
class RandAugment(): def __init__(self, ops, num_layers=2, choice_weights=None): self.ops = ops self.num_layers = num_layers self.choice_weights = choice_weights def __call__(self, img): ops = np.random.choice(self.ops, self.num_layers, replace=(self.choice_weights is None), ...
def rand_augment_transform(config_str, hparams): "\n RandAugment: Practical automated data augmentation... - https://arxiv.org/abs/1909.13719\n\n Create a RandAugment transform\n :param config_str: String defining configuration of random augmentation. Consists of multiple sections separated by\n dashe...
class RawVideoExtractorCV2(): def __init__(self, centercrop=False, size=224, framerate=(- 1), subset='test'): self.centercrop = centercrop self.size = size self.framerate = framerate self.transform = self._transform(self.size) self.subset = subset self.tsfm_dict = ...
def url_to_filename(url: str, etag: str=None) -> str: "\n Convert `url` into a hashed filename in a repeatable way.\n If `etag` is specified, append its hash to the url's, delimited\n by a period.\n " url_bytes = url.encode('utf-8') url_hash = sha256(url_bytes) filename = url_hash.hexdiges...
def filename_to_url(filename: str, cache_dir: Union[(str, Path)]=None) -> Tuple[(str, str)]: '\n Return the url and etag (which may be ``None``) stored for `filename`.\n Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.\n ' if (cache_dir is None): cache_dir = PYTO...
def cached_path(url_or_filename: Union[(str, Path)], cache_dir: Union[(str, Path)]=None) -> str: "\n Given something that might be a URL (or might be a local path),\n determine which. If it's a URL, download the file and cache it, and\n return the path to the cached file. If it's already a local path,\n ...
def split_s3_path(url: str) -> Tuple[(str, str)]: 'Split a full s3 path into the bucket name and path.' parsed = urlparse(url) if ((not parsed.netloc) or (not parsed.path)): raise ValueError('bad s3 path {}'.format(url)) bucket_name = parsed.netloc s3_path = parsed.path if s3_path.star...
def s3_request(func: Callable): '\n Wrapper function for s3 requests in order to create more helpful error\n messages.\n ' @wraps(func) def wrapper(url: str, *args, **kwargs): try: return func(url, *args, **kwargs) except ClientError as exc: if (int(exc.re...
@s3_request def s3_etag(url: str) -> Optional[str]: 'Check ETag on S3 object.' s3_resource = boto3.resource('s3') (bucket_name, s3_path) = split_s3_path(url) s3_object = s3_resource.Object(bucket_name, s3_path) return s3_object.e_tag
@s3_request def s3_get(url: str, temp_file: IO) -> None: 'Pull a file directly from S3.' s3_resource = boto3.resource('s3') (bucket_name, s3_path) = split_s3_path(url) s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
def http_get(url: str, temp_file: IO) -> None: req = requests.get(url, stream=True) content_length = req.headers.get('Content-Length') total = (int(content_length) if (content_length is not None) else None) progress = tqdm(unit='B', total=total) for chunk in req.iter_content(chunk_size=1024): ...
def get_from_cache(url: str, cache_dir: Union[(str, Path)]=None) -> str: "\n Given a URL, look for the corresponding dataset in the local cache.\n If it's not there, download it. Then return the path to the cached file.\n " if (cache_dir is None): cache_dir = PYTORCH_PRETRAINED_BERT_CACHE ...
def read_set_from_file(filename: str) -> Set[str]: '\n Extract a de-duped collection (set) of text from a file.\n Expected file format is one item per line.\n ' collection = set() with open(filename, 'r', encoding='utf-8') as file_: for line in file_: collection.add(line.rstri...
def get_file_extension(path: str, dot=True, lower: bool=True): ext = os.path.splitext(path)[1] ext = (ext if dot else ext[1:]) return (ext.lower() if lower else ext)
class LayerNorm(nn.LayerNorm): "Subclass torch's LayerNorm to handle fp16." def forward(self, x: torch.Tensor): orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type)
class QuickGELU(nn.Module): def forward(self, x: torch.Tensor): return (x * torch.sigmoid((1.702 * x)))
class ResidualAttentionBlock(nn.Module): def __init__(self, d_model: int, n_head: int, attn_mask=None): super(ResidualAttentionBlock, self).__init__() self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([('c_fc', n...
class Transformer(nn.Module): def __init__(self, width: int, layers: int, heads: int, attn_mask=None): super(Transformer, self).__init__() self.width = width self.layers = layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads) for _ in range(layers)]) de...
def warmup_cosine(x, warmup=0.002): if (x < warmup): return (x / warmup) return (0.5 * (1.0 + math.cos((math.pi * x))))
def warmup_constant(x, warmup=0.002): ' Linearly increases learning rate over `warmup`*`t_total` (as provided to BertAdam) training steps.\n Learning rate is 1. afterwards. ' if (x < warmup): return (x / warmup) return 1.0
def warmup_linear(x, warmup=0.002): ' Specifies a triangular learning rate schedule where peak is reached at `warmup`*`t_total`-th (as provided to BertAdam) training step.\n After `t_total`-th training step, learning rate is zero. ' if (x < warmup): return (x / warmup) return max(((x - 1.0)...
class BertAdam(Optimizer): "Implements BERT version of Adam algorithm with weight decay fix.\n Params:\n lr: learning rate\n warmup: portion of t_total for the warmup, -1 means no warmup. Default: -1\n t_total: total number of training steps for the learning\n rate schedule, -1...
@lru_cache() def default_bpe(): return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bpe_simple_vocab_16e6.txt.gz')
@lru_cache() def bytes_to_unicode(): "\n Returns list of utf-8 byte and a corresponding list of unicode strings.\n The reversible bpe codes work on unicode strings.\n This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.\n When you're at something like a 10B toke...
def get_pairs(word): 'Return set of symbol pairs in a word.\n Word is represented as tuple of symbols (symbols being variable-length strings).\n ' pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
def basic_clean(text): text = ftfy.fix_text(text) text = html.unescape(html.unescape(text)) return text.strip()
def whitespace_clean(text): text = re.sub('\\s+', ' ', text) text = text.strip() return text
class SimpleTokenizer(object): def __init__(self, bpe_path: str=default_bpe()): self.byte_encoder = bytes_to_unicode() self.byte_decoder = {v: k for (k, v) in self.byte_encoder.items()} merges = gzip.open(bpe_path).read().decode('utf-8').split('\n') merges = merges[1:(((49152 - 25...
class PretrainedConfig(object): pretrained_model_archive_map = {} config_name = '' weights_name = '' @classmethod def get_config(cls, pretrained_model_name, cache_dir, type_vocab_size, state_dict, task_config=None): archive_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), p...
def get_world_size(): if (not dist.is_available()): return 1 if (not dist.is_initialized()): return 1 return dist.get_world_size()
def get_rank(): if (not dist.is_available()): return 0 if (not dist.is_initialized()): return 0 return dist.get_rank()
def is_main_process(): return (get_rank() == 0)
def synchronize(): '\n Helper function to synchronize (barrier) among all processes when\n using distributed training\n ' if (not dist.is_available()): return if (not dist.is_initialized()): return world_size = dist.get_world_size() if (world_size == 1): return ...
def all_gather(data): '\n Run all_gather on arbitrary picklable data (not necessarily tensors)\n Args:\n data: any picklable object\n Returns:\n list[data]: list of data gathered from each rank\n ' world_size = get_world_size() if (world_size == 1): return [data] buff...
def reduce_dict(input_dict, average=True): '\n Args:\n input_dict (dict): all the values will be reduced\n average (bool): whether to do average or sum\n Reduce the values in the dictionary from all processes so that process with rank\n 0 has the averaged results. Returns a dict with the sa...
def setup_logger(name, save_dir, dist_rank, filename='log.txt'): logger = logging.getLogger(name) logger.setLevel(logging.ERROR) if (dist_rank > 0): return logger logger.setLevel(logging.DEBUG) ch = logging.StreamHandler(stream=sys.stdout) ch.setLevel(logging.DEBUG) formatter = log...
class SmoothedValue(object): 'Track a series of values and provide access to smoothed values over a\n window or the global series average.\n ' def __init__(self, window_size=20): self.deque = deque(maxlen=window_size) self.series = [] self.total = 0.0 self.count = 0 ...
class MetricLogger(object): def __init__(self, delimiter='\t'): self.meters = defaultdict(SmoothedValue) self.delimiter = delimiter def update(self, **kwargs): for (k, v) in kwargs.items(): if isinstance(v, torch.Tensor): v = v.item() assert is...
class AverageMeter(object): 'Computes and stores the average and current value' def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += (val...
def accuracy(output, target, topk=(1,)): 'Computes the precision@k for the specified values of k' with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) (_, pred) = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, (- 1)).expa...
def get_a_var(obj): if isinstance(obj, torch.Tensor): return obj if (isinstance(obj, list) or isinstance(obj, tuple)): for result in map(get_a_var, obj): if isinstance(result, torch.Tensor): return result if isinstance(obj, dict): for result in map(get_a...
def parallel_apply(fct, model, inputs, device_ids): modules = nn.parallel.replicate(model, device_ids) assert (len(modules) == len(inputs)) lock = threading.Lock() results = {} grad_enabled = torch.is_grad_enabled() def _worker(i, module, input): torch.set_grad_enabled(grad_enabled) ...
def get_logger(filename=None): logger = logging.getLogger('logger') logger.setLevel(logging.DEBUG) logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) if (filename is not None): handler = logging.FileHandler(filename) ...
def convert_module_to_f16(l): '\n Convert primitive modules to float16.\n ' if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): l.weight.data = l.weight.data.half() if (l.bias is not None): l.bias.data = l.bias.data.half()
def convert_module_to_f32(l): '\n Convert primitive modules to float32, undoing convert_module_to_f16().\n ' if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): l.weight.data = l.weight.data.float() if (l.bias is not None): l.bias.data = l.bias.data.float()
def make_master_params(param_groups_and_shapes): '\n Copy model parameters into a (differently-shaped) list of full-precision\n parameters.\n ' master_params = [] for (param_group, shape) in param_groups_and_shapes: master_param = nn.Parameter(_flatten_dense_tensors([param.detach().float(...
def model_grads_to_master_grads(param_groups_and_shapes, master_params): '\n Copy the gradients from the model parameters into the master parameters\n from make_master_params().\n ' for (master_param, (param_group, shape)) in zip(master_params, param_groups_and_shapes): master_param.grad = _f...
def master_params_to_model_params(param_groups_and_shapes, master_params): '\n Copy the master parameter data back into the model parameters.\n ' for (master_param, (param_group, _)) in zip(master_params, param_groups_and_shapes): for ((_, param), unflat_master_param) in zip(param_group, unflatt...
def unflatten_master_params(param_group, master_param): return _unflatten_dense_tensors(master_param, [param for (_, param) in param_group])
def get_param_groups_and_shapes(named_model_params): named_model_params = list(named_model_params) scalar_vector_named_params = ([(n, p) for (n, p) in named_model_params if (p.ndim <= 1)], (- 1)) matrix_named_params = ([(n, p) for (n, p) in named_model_params if (p.ndim > 1)], (1, (- 1))) return [scal...
def master_params_to_state_dict(model, param_groups_and_shapes, master_params, use_fp16): if use_fp16: state_dict = model.state_dict() for (master_param, (param_group, _)) in zip(master_params, param_groups_and_shapes): for ((name, _), unflat_master_param) in zip(param_group, unflatten...
def state_dict_to_master_params(model, state_dict, use_fp16): if use_fp16: named_model_params = [(name, state_dict[name]) for (name, _) in model.named_parameters()] param_groups_and_shapes = get_param_groups_and_shapes(named_model_params) master_params = make_master_params(param_groups_and...
def zero_master_grads(master_params): for param in master_params: param.grad = None
def zero_grad(model_params): for param in model_params: if (param.grad is not None): param.grad.detach_() param.grad.zero_()
def param_grad_or_zeros(param): if (param.grad is not None): return param.grad.data.detach() else: return th.zeros_like(param)
class MixedPrecisionTrainer(): def __init__(self, *, model, use_fp16=False, fp16_scale_growth=0.001, initial_lg_loss_scale=INITIAL_LOG_LOSS_SCALE): self.model = model self.use_fp16 = use_fp16 self.fp16_scale_growth = fp16_scale_growth self.model_params = list(self.model.parameters...
def check_overflow(value): return ((value == float('inf')) or (value == (- float('inf'))) or (value != value))
def get_named_beta_schedule(schedule_name, num_diffusion_timesteps): '\n Get a pre-defined beta schedule for the given name.\n\n The beta schedule library consists of beta schedules which remain similar\n in the limit of num_diffusion_timesteps.\n Beta schedules may be added, but should not be removed...
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): '\n Create a beta schedule that discretizes the given alpha_t_bar function,\n which defines the cumulative product of (1-beta) over time from t = [0,1].\n\n :param num_diffusion_timesteps: the number of betas to produce.\n :p...
class ModelMeanType(enum.Enum): '\n Which type of output the model predicts.\n ' PREVIOUS_X = enum.auto() START_X = enum.auto() EPSILON = enum.auto()
class ModelVarType(enum.Enum): "\n What is used as the model's output variance.\n\n The LEARNED_RANGE option has been added to allow the model to predict\n values between FIXED_SMALL and FIXED_LARGE, making its job easier.\n " LEARNED = enum.auto() FIXED_SMALL = enum.auto() FIXED_LARGE = e...
class LossType(enum.Enum): MSE = enum.auto() RESCALED_MSE = enum.auto() KL = enum.auto() RESCALED_KL = enum.auto() def is_vb(self): return ((self == LossType.KL) or (self == LossType.RESCALED_KL))
class GaussianDiffusion(): '\n Utilities for training and sampling diffusion models.\n\n Ported directly from here, and then adapted over time to further experimentation.\n https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42\n\n ...
def _extract_into_tensor(arr, timesteps, broadcast_shape): '\n Extract values from a 1-D numpy array for a batch of indices.\n\n :param arr: the 1-D numpy array.\n :param timesteps: a tensor of indices into the array to extract.\n :param broadcast_shape: a larger shape of K dimensions with the batch\n...
class KVWriter(object): def writekvs(self, kvs): raise NotImplementedError
class SeqWriter(object): def writeseq(self, seq): raise NotImplementedError
class HumanOutputFormat(KVWriter, SeqWriter): def __init__(self, filename_or_file): if isinstance(filename_or_file, str): self.file = open(filename_or_file, 'wt') self.own_file = True else: assert hasattr(filename_or_file, 'read'), ('expected file or str, got %...
class JSONOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, 'wt') def writekvs(self, kvs): for (k, v) in sorted(kvs.items()): if hasattr(v, 'dtype'): kvs[k] = float(v) self.file.write((json.dumps(kvs) + '\n')) self.fi...
class CSVOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, 'w+t') self.keys = [] self.sep = ',' def writekvs(self, kvs): extra_keys = list((kvs.keys() - self.keys)) extra_keys.sort() if extra_keys: self.keys.extend(ex...
class TensorBoardOutputFormat(KVWriter): "\n Dumps key/value pairs into TensorBoard's numeric format.\n " def __init__(self, dir): os.makedirs(dir, exist_ok=True) self.dir = dir self.step = 1 prefix = 'events' path = osp.join(osp.abspath(dir), prefix) imp...
def make_output_format(format, ev_dir, log_suffix=''): os.makedirs(ev_dir, exist_ok=True) if (format == 'stdout'): return HumanOutputFormat(sys.stdout) elif (format == 'log'): return HumanOutputFormat(osp.join(ev_dir, ('log%s.txt' % log_suffix))) elif (format == 'json'): return...
def logkv(key, val): '\n Log a value of some diagnostic\n Call this once for each diagnostic quantity, each iteration\n If called many times, last value will be used.\n ' get_current().logkv(key, val)
def logkv_mean(key, val): '\n The same as logkv(), but if called many times, values averaged.\n ' get_current().logkv_mean(key, val)
def logkvs(d): '\n Log a dictionary of key-value pairs\n ' for (k, v) in d.items(): logkv(k, v)
def dumpkvs(): '\n Write all of the diagnostics from the current iteration\n ' return get_current().dumpkvs()
def getkvs(): return get_current().name2val
def log(*args, level=INFO): "\n Write the sequence of args, with no separators, to the console and output files (if you've configured an output file).\n " get_current().log(*args, level=level)
def debug(*args): log(*args, level=DEBUG)
def info(*args): log(*args, level=INFO)
def warn(*args): log(*args, level=WARN)
def error(*args): log(*args, level=ERROR)
def set_level(level): '\n Set logging threshold on current logger.\n ' get_current().set_level(level)