python_code stringlengths 0 258k |
|---|
## Base Exceptions
class HTTPError(Exception):
"Base exception used by this module."
pass
class HTTPWarning(Warning):
"Base warning used by this module."
pass
class PoolError(HTTPError):
"Base exception for errors caused within a pool."
def __init__(self, pool, message):
self.pool ... |
import errno
import logging
import sys
import warnings
from socket import error as SocketError, timeout as SocketTimeout
import socket
try: # Python 3
from queue import LifoQueue, Empty, Full
except ImportError:
from Queue import LifoQueue, Empty, Full
import Queue as _ # Platform-specific: Windows
fr... |
from base64 import b64encode
from ..packages.six import b
ACCEPT_ENCODING = 'gzip,deflate'
def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,
basic_auth=None, proxy_basic_auth=None, disable_cache=None):
"""
Shortcuts for generating request headers.
:param keep_ali... |
# The default socket timeout, used by httplib to indicate that no timeout was
# specified by the user
from socket import _GLOBAL_DEFAULT_TIMEOUT
import time
from ..exceptions import TimeoutStateError
# A sentinel value to indicate that no timeout was specified by the user in
# urllib3
_Default = object()
def current... |
# For backwards compatibility, provide imports that used to be here.
from .connection import is_connection_dropped
from .request import make_headers
from .response import is_fp_closed
from .ssl_ import (
SSLContext,
HAS_SNI,
assert_fingerprint,
resolve_cert_reqs,
resolve_ssl_version,
ssl_wrap_so... |
def is_fp_closed(obj):
"""
Checks whether a given file-like object is closed.
:param obj:
The file-like object to check.
"""
try:
# Check via the official file-like-object way.
return obj.closed
except AttributeError:
pass
try:
# Check if the object... |
from binascii import hexlify, unhexlify
from hashlib import md5, sha1, sha256
from ..exceptions import SSLError, InsecurePlatformWarning
SSLContext = None
HAS_SNI = False
create_default_context = None
import errno
import warnings
try: # Test for SSL features
import ssl
from ssl import wrap_socket, CERT_NO... |
import time
import logging
from ..exceptions import (
ConnectTimeoutError,
MaxRetryError,
ProtocolError,
ReadTimeoutError,
ResponseError,
)
from ..packages import six
log = logging.getLogger(__name__)
class Retry(object):
""" Retry configuration.
Each retry attempt will create a new Re... |
from collections import namedtuple
from ..exceptions import LocationParseError
url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']
class Url(namedtuple('Url', url_attrs)):
"""
Datastructure for representing an HTTP URL. Used as a return value for
:func:`parse_url`.
"""
s... |
import socket
try:
from select import poll, POLLIN
except ImportError: # `poll` doesn't exist on OSX and other platforms
poll = False
try:
from select import select
except ImportError: # `select` doesn't exist on AppEngine.
select = False
def is_connection_dropped(conn): # Platform-... |
'''SSL with SNI_-support for Python 2. Follow these instructions if you would
like to verify SSL certificates in Python 2. Note, the default libraries do
*not* do certificate checking; you need to do additional work to validate
certificates yourself.
This needs the following packages installed:
* pyOpenSSL (tested wi... |
"""
NTLM authenticating pool, contributed by erikcederstran
Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10
"""
try:
from http.client import HTTPSConnection
except ImportError:
from httplib import HTTPSConnection
from logging import getLogger
from ntlm import ntlm
from urllib3 import HTT... |
from __future__ import absolute_import
from . import ssl_match_hostname
|
# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
# Passes Python2.7's test suite and incorporates all the latest updates.
# Copyright 2009 Raymond Hettinger, released under the MIT License.
# http://code.activestate.com/recipes/576693/
try:
from thread import get_ident as _get_iden... |
"""Utilities for writing code that runs on Python 2 and 3"""
#Copyright (c) 2010-2011 Benjamin Peterson
#Permission is hereby granted, free of charge, to any person obtaining a copy of
#this software and associated documentation files (the "Software"), to deal in
#the Software without restriction, including without l... |
try:
# Python 3.2+
from ssl import CertificateError, match_hostname
except ImportError:
try:
# Backport of the function from a pypi module
from backports.ssl_match_hostname import CertificateError, match_hostname
except ImportError:
# Our vendored copy
from ._implementati... |
"""The match_hostname() function from Python 3.3.3, essential when using SSL."""
# Note: This file is under the PSF license as the code comes from the python
# stdlib. http://docs.python.org/3/license.html
import re
__version__ = '3.4.0.2'
class CertificateError(ValueError):
pass
def _dnsname_match(dn, host... |
# -*- coding: utf-8 -*-
#
# GHC Users Guide documentation build configuration file
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
import sys
import os
import sphinx_rtd_theme
# Support for :base-ref:, etc.
sys.path.insert(0, os.path.abspath('.'))
import cabaldomain
version = "1... |
# -*- coding: utf-8 -*-
'''
Sphinx domain for documenting all things cabal
The main reason to use this instead of adding object types to std domain
is the ability to generate nice 'Reference' page and also provide some meta
data for objects described with directives described here.
Most directives have at least follo... |
#! /usr/bin/env python
#
# Copyright (C) 2010 Joel Rosdahl
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
#
# This pr... |
from setuptools import setup
if __name__ == "__main__":
setup()
|
r"""Run a submission on a single workload.
Example command:
# pylint: disable=line-too-long
python3 submission_runner.py \
--workload=mnist \
--framework=jax \
--submission_path=reference_algorithms/development_algorithms/mnist/mnist_jax/submission.py \
--tuning_ruleset=external \
--tuning_search_... |
import jax
print('JAX identified %d GPU devices' % jax.local_device_count())
print('Generating RNG seed for CUDA sanity check ... ')
rng = jax.random.PRNGKey(0)
data_rng, shuffle_rng = jax.random.split(rng, 2)
if jax.local_device_count() == 8 and data_rng is not None:
print('Woohoo 8 GPUs present and CUDA works!!')... |
import jax.dlpack
import torch
from algorithmic_efficiency import spec
def jax_to_pytorch(x: spec.Tensor, take_ownership: bool = False) -> spec.Tensor:
return torch.utils.dlpack.from_dlpack(
jax.dlpack.to_dlpack(x, take_ownership=take_ownership))
def pytorch_to_jax(x: torch.Tensor) -> spec.Tensor:
x = x.... |
import os
from typing import Tuple
from absl import logging
import jax
import tensorflow as tf
import torch
import torch.distributed as dist
from algorithmic_efficiency import spec
from algorithmic_efficiency.profiler import Profiler
from algorithmic_efficiency.workloads.librispeech_conformer.librispeech_pytorch.mode... |
"""Proxy functions in front of the Jax RNG API or a compatible Numpy RNG API."""
from typing import Any, List, Union
from absl import flags
from absl import logging
import numpy as np
try:
import jax.random as jax_rng
except (ImportError, ModuleNotFoundError):
logging.warning(
'Could not import jax.random ... |
"""Algorithmic Efficiency."""
__version__ = '0.0.1'
|
"""MLPerf™ Algorithmic Efficiency API."""
import abc
import enum
import functools
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union
from absl import logging
import jax
from torch import nn
import torch.nn.functional as F
class LossType(enum.Enum):
SOFTMAX_CROSS_ENTROPY = 0
SIGMOID_C... |
"""Utilities for initializing parameters.
Note: Code adapted from
https://github.com/google/jax/blob/main/jax/_src/nn/initializers.py.
"""
import math
from torch import nn
def pytorch_default_init(module: nn.Module) -> None:
# Perform lecun_normal initialization.
fan_in, _ = nn.init._calculate_fan_in_and_fan_o... |
"""Hyperparameter sweeps with Halton sequences of quasi-random numbers.
Based off the algorithms described in https://arxiv.org/abs/1706.03200. Inspired
by the code in
https://github.com/google/uncertainty-baselines/blob/master/uncertainty_baselines/halton.py
written by the same authors.
"""
import collections
import... |
"""Utilities for data processing."""
from typing import Dict, Iterable, Optional, Tuple
import jax
import numpy as np
import torch
import torch.distributed as dist
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data import DistributedSampler
from torch.utils.data import Sampl... |
"""Utilities for dealing with parameter-related logic like types and shapes."""
from typing import Dict
import flax
import jax
from torch import nn
from algorithmic_efficiency import spec
def pytorch_param_shapes(model: nn.Module) -> Dict[str, spec.ShapeTuple]:
return {k: spec.ShapeTuple(v.shape) for k, v in mod... |
"""Utilities for checkpointing.
Note: Code adapted from
https://github.com/google/init2winit/blob/master/init2winit/checkpoint.py.
"""
import os
from typing import Sequence, Tuple
from absl import logging
from flax import jax_utils
from flax.training import checkpoints as flax_checkpoints
from flax.training.checkpoi... |
"""Utilities for logging."""
import collections
import json
import logging
import os.path
import platform
import re
import shutil
import subprocess
import sys
from typing import Any, Optional
from absl import flags
from clu import metric_writers
import GPUtil
import pandas as pd
import psutil
from algorithmic_effici... |
"""Profiling code for Jax and PyTorch.
Modified from:
https://github.com/Lightning-AI/lightning/tree/master/src/pytorch_lightning/profilers.
"""
from collections import defaultdict
from contextlib import contextmanager
import os
import time
from typing import Dict, Generator, List, Optional, Tuple
import numpy as np... |
""" Registry of workload info
"""
import importlib
import inspect
import os
from algorithmic_efficiency import spec
BASE_WORKLOADS_DIR = 'algorithmic_efficiency/workloads/'
WORKLOADS = {
'cifar': {
'workload_path': 'cifar/cifar', 'workload_class_name': 'CifarWorkload'
},
'criteo1tb': {
'w... |
"""MNIST workload parent class."""
import abc
import functools
import math
from typing import Any, Dict, Iterator, Optional
import jax
import tensorflow as tf
import tensorflow_datasets as tfds
import torch
from algorithmic_efficiency import data_utils
from algorithmic_efficiency import spec
from algorithmic_efficie... |
"""MNIST workload implemented in Jax."""
import functools
from typing import Any, Dict, Optional, Tuple
from flax import jax_utils
from flax import linen as nn
import jax
from jax import lax
import jax.numpy as jnp
import optax
from algorithmic_efficiency import param_utils
from algorithmic_efficiency import spec
fr... |
"""MNIST workload implemented in PyTorch."""
from collections import OrderedDict
import contextlib
from typing import Any, Dict, Iterator, Optional, Tuple
import torch
from torch import nn
import torch.distributed as dist
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
fr... |
from algorithmic_efficiency.workloads.librispeech_conformer import workload
class BaseDeepspeechLibrispeechWorkload(workload.BaseLibrispeechWorkload):
@property
def validation_target_value(self) -> float:
return 0.1162
@property
def test_target_value(self) -> float:
return 0.068093
@property
de... |
r"""Deepspeech.
This model uses a deepspeech2 network to convert speech to text.
paper : https://arxiv.org/abs/1512.02595
# BiLSTM code contributed by bastings@
# github : https://github.com/bastings
# webpage : https://bastings.github.io/
"""
from typing import Any, Dict, List, Optional, Tuple, Union
from flax imp... |
import functools
from typing import Optional
from flax import jax_utils
import jax
import jax.numpy as jnp
import numpy as np
from algorithmic_efficiency import param_utils
from algorithmic_efficiency import spec
from algorithmic_efficiency.workloads.librispeech_conformer.librispeech_jax.workload import \
LibriSp... |
"""This is a pytorch implementation mirroring:
https://github.com/google/init2winit/blob/master/init2winit/model_lib/conformer.py.
"""
from dataclasses import dataclass
import os
from typing import Optional, Tuple
import torch
from torch import nn
import torch.distributed.nn as dist_nn
import torch.nn.functional as F... |
from typing import Optional
import torch
from torch.nn.parallel import DistributedDataParallel as DDP
from algorithmic_efficiency import param_utils
from algorithmic_efficiency import spec
from algorithmic_efficiency.pytorch_utils import pytorch_setup
from algorithmic_efficiency.workloads.librispeech_conformer.libris... |
"""Input pipeline for a WMT dataset."""
import functools
import os
from typing import Dict, List, Optional, Union
import tensorflow as tf
import tensorflow_datasets as tfds
from algorithmic_efficiency import data_utils
from algorithmic_efficiency.pytorch_utils import pytorch_setup
from algorithmic_efficiency.workload... |
from itertools import zip_longest
from typing import Sequence
from absl import logging
import sacrebleu
import torch
import torch.distributed as dist
from algorithmic_efficiency.pytorch_utils import pytorch_setup
USE_PYTORCH_DDP, _, DEVICE, N_GPUS = pytorch_setup()
# Modified (added sync for PyTorch DDP) from
# ht... |
"""WMT workload parent class."""
import abc
import math
import os
from typing import Any, Dict, Optional, Tuple
import jax
import numpy as np
import torch
from algorithmic_efficiency import spec
from algorithmic_efficiency.workloads.wmt import input_pipeline
from algorithmic_efficiency.workloads.wmt.wmt_jax import d... |
"""Provides op for tokenizing a dataset.
Modified from https://github.com/google/flax/tree/main/examples/wmt.
"""
import dataclasses
import os
import tempfile
import time
from typing import Any, Dict, Iterable, Tuple
from absl import logging
import jax
from sentencepiece import SentencePieceTrainer
import tensorflow... |
import copy
import math
from typing import Any, Callable, Dict, Optional, Tuple, Union
import warnings
import torch
from torch import nn
from torch import Tensor
import torch.nn.functional as F
from torch.nn.init import normal_
from torch.nn.init import xavier_uniform_
# Mask making utilities ported to PyTorch from
... |
"""WMT workload implemented in PyTorch."""
import contextlib
from typing import Any, Dict, Optional, Tuple
from absl import logging
import jax
import tensorflow as tf
import torch
import torch.distributed as dist
from torch.nn import DataParallel as DP
from torch.nn.parallel import DistributedDataParallel as DDP
fro... |
"""Fast decoding routines for inference from a trained model.
PyTorch port of https://github.com/google/flax/tree/main/examples/wmt.
"""
from dataclasses import dataclass
from typing import Any, Callable, Dict, Optional, Tuple, Union
import jax
import torch
import torch.nn.functional as F
from algorithmic_efficienc... |
"""Transformer-based machine translation model.
Reference https://github.com/google/flax/tree/main/examples/wmt.
"""
from typing import Any, Callable, Optional
from flax import linen as nn
from flax import struct
from jax import lax
import jax.numpy as jnp
import numpy as np
@struct.dataclass
class TransformerConf... |
"""WMT workload implemented in Jax."""
import functools
from typing import Any, Dict, Iterator, Optional, Tuple
from absl import logging
from flax import jax_utils
from flax import linen as nn
from flax.training import common_utils
import jax
import jax.numpy as jnp
import numpy as np
import optax
from algorithmic_ef... |
"""Fast decoding routines for inference from a trained model.
Forked from https://github.com/google/flax/tree/main/examples/wmt.
"""
import typing
import flax
import jax
from jax import lax
import jax.numpy as jnp
import numpy as np
# Constants
# We assume the default End-of-Sentence token id is 2 (SentencePiece).
... |
"""ImageNet ViT workload."""
from typing import Dict, Iterator, Optional
from algorithmic_efficiency import spec
from algorithmic_efficiency.workloads.imagenet_resnet.workload import \
BaseImagenetResNetWorkload
def decode_variant(variant: str) -> Dict[str, int]:
"""Converts a string like 'B/32' into a params... |
"""PyTorch implementation of refactored and simplified ViT.
Adapted from:
https://github.com/huggingface/transformers/tree/main/src/transformers/models/vit.
https://github.com/lucidrains/vit-pytorch.
"""
import math
from typing import Any, Optional, Tuple, Union
import torch
from torch import nn
import torch.nn.func... |
"""ImageNet ViT workload implemented in PyTorch."""
import contextlib
from typing import Dict, Optional, Tuple
import torch
from torch.nn.parallel import DistributedDataParallel as DDP
from algorithmic_efficiency import param_utils
from algorithmic_efficiency import pytorch_utils
from algorithmic_efficiency import s... |
"""Jax implementation of refactored and simplified ViT.
Forked from:
https://github.com/google/init2winit/blob/master/init2winit/model_lib/vit.py,
originally from https://github.com/google/big_vision with modifications noted.
"""
from typing import Optional, Sequence, Union
from flax import linen as nn
import jax.nu... |
"""ImageNet workload implemented in Jax."""
from typing import Dict, Optional, Tuple
from flax import jax_utils
from flax import linen as nn
import jax
import jax.numpy as jnp
from algorithmic_efficiency import param_utils
from algorithmic_efficiency import spec
from algorithmic_efficiency.workloads.imagenet_resnet.... |
from clu import metrics
import flax
import numpy as np
import tensorflow as tf
import tensorflow_text as tftxt
gfile = tf.io.gfile
def average_ctc_loss():
"""Returns a clu.Metric that computes average CTC loss
taking padding into account.
"""
@flax.struct.dataclass
class _Metric(metrics.Metric):
"""Ap... |
"""Sharing the jax input pipeline slows down the data loading
and step times.
"""
import csv
from absl import logging
import numpy as np
import torch
class LibriSpeechDataset(torch.utils.data.Dataset):
def __init__(self, split, data_dir):
super().__init__()
self.data_dir = data_dir
splits = split.spl... |
import math
from typing import Dict
from algorithmic_efficiency import spec
class BaseLibrispeechWorkload(spec.Workload):
_num_outputs: int = 1024
@property
def target_metric_name(self) -> str:
"""The name of the target metric (useful for scoring/processing code)."""
return 'wer'
def has_reached_v... |
"""A flax layer to do data augmentation for audio signals as
described in https://arxiv.org/abs/1904.08779.
Code based on:
github.com/tensorflow/lingvo/blob/master/lingvo/jax/layers/spectrum_augmenter.py
"""
import flax.linen as nn
import jax
import jax.numpy as jnp
class SpecAug(nn.Module):
"""Layer performs mas... |
r"""Conformer.
This model uses a conformer network to convert speech to text.
paper : https://arxiv.org/abs/2005.08100
high-level overview of Conformer encoder layer.
x = x + 0.5 * FeedForward(x)
x = x + MHSA(x)
x = x + ConvolutionBlock(x)
x = x + 0.5 * FeedForward(x)
y = layer_norm(x)
"""
import math
fro... |
import functools
import math
from typing import Dict, Iterator, Optional, Tuple
from flax import jax_utils
import flax.linen as nn
import jax
from jax import lax
import jax.numpy as jnp
import numpy as np
import optax
import torch
from algorithmic_efficiency import data_utils
from algorithmic_efficiency import param_... |
"""Flax layer to perform preprocessing on librispeech audio inputs.
This layer computes windowed short time fourier transform over audio signals
then converts it to mel scale and finally takes a logarithm of resulting
mel spectrograms and normalizes it to be used in speech recognition models.
This code is based on li... |
"""This is a pytorch implementation mirroring:
https://github.com/google/init2winit/blob/master/init2winit/model_lib/spectrum_augmenter.py.
"""
import torch
from torch import nn
class SpecAug(nn.Module):
"""Layer performs masking prodecure along time and frequency axis.
The procedure is detailed in https://ar... |
"""This is a pytorch implementation mirroring:
https://github.com/google/init2winit/blob/master/init2winit/model_lib/conformer.py.
"""
from dataclasses import dataclass
import math
from typing import Tuple
import torch
from torch import nn
from torch.nn import init
import torch.nn.functional as F
from algorithmic_ef... |
"""This is a pytorch implementation mirroring:
https://github.com/google/init2winit/blob/master/init2winit/model_lib/librispeech_preprocessor.py.
"""
from dataclasses import dataclass
import math
from typing import Any, Optional, Union
import numpy as np
import torch
from torch import nn
import torch.nn.functional as... |
"""Conformer workload implemented in PyTorch."""
import contextlib
import functools
import math
import random
from typing import Dict, Iterator, Optional, Tuple
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from algorithmic_efficiency import data_utils
fro... |
# Forked from Flax example which can be found here:
# https://github.com/google/flax/blob/main/examples/ogbg_molpcba/train.py
from typing import Any
from clu import metrics
import flax
import jax
import jax.numpy as jnp
import numpy as np
from sklearn.metrics import average_precision_score
import torch
import torch.di... |
# Forked from Flax example which can be found here:
# https://github.com/google/flax/blob/main/examples/ogbg_molpcba/input_pipeline.py
# and from the init2winit fork here
# https://github.com/google/init2winit/blob/master/init2winit/dataset_lib/ogbg_molpcba.py
"""Exposes the ogbg-molpcba dataset in a convenient format.... |
"""OGBG workload parent class."""
import abc
import itertools
import math
from typing import Any, Dict, Optional
import jax
from algorithmic_efficiency import random_utils as prng
from algorithmic_efficiency import spec
from algorithmic_efficiency.workloads.ogbg import input_pipeline
from algorithmic_efficiency.work... |
# Ported to PyTorch from
# https://github.com/google/init2winit/blob/master/init2winit/model_lib/gnn.py.
from typing import Callable, Optional, Tuple
import jax.tree_util as tree
from jraph import GraphsTuple
import torch
from torch import nn
from algorithmic_efficiency import init_utils
def _make_mlp(in_dim, hidde... |
"""OGBG workload implemented in PyTorch."""
import contextlib
from typing import Any, Callable, Dict, Optional, Tuple
import jax
from jraph import GraphsTuple
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from algorithmic_efficiency import param_utils
from ... |
# Forked from the init2winit implementation here
# https://github.com/google/init2winit/blob/master/init2winit/model_lib/gnn.py.
from typing import Optional, Tuple
from flax import linen as nn
import jax.numpy as jnp
import jraph
def _make_embed(latent_dim, name):
def make_fn(inputs):
return nn.Dense(features... |
"""OGBG workload implemented in Jax."""
import functools
from typing import Any, Dict, Optional, Tuple
from flax import jax_utils
import jax
import jax.numpy as jnp
import jraph
import optax
from algorithmic_efficiency import param_utils
from algorithmic_efficiency import spec
from algorithmic_efficiency.workloads.og... |
"""ImageNet workload parent class."""
import math
from typing import Dict, Iterator, Optional, Tuple
from algorithmic_efficiency import spec
class BaseImagenetResNetWorkload(spec.Workload):
_num_classes: int = 1000
@property
def target_metric_name(self) -> str:
"""The name of the target metric (useful f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.