uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
f818e9ef7768e8fb1f632d90
train
function
def funcC(sigma, z): C = np.zeros(len(z), dtype='complex128') for i in range(len(C)): for k in range(len(C)): if i!=k: C[i]+= sigma[i]*sigma[k] / (np.conj(z[i]) - np.conj(z[k])) # z_ = np.conj(z) # C = np.outer(sigma,sigma)/(np.outer(z_,np.ones(z_.shape)) - np.outer(n...
def funcC(sigma, z):
C = np.zeros(len(z), dtype='complex128') for i in range(len(C)): for k in range(len(C)): if i!=k: C[i]+= sigma[i]*sigma[k] / (np.conj(z[i]) - np.conj(z[k])) # z_ = np.conj(z) # C = np.outer(sigma,sigma)/(np.outer(z_,np.ones(z_.shape)) - np.outer(np.ones(z_.shape),z_))...
import numpy as np from scipy.spatial.distance import cdist from tqdm import tqdm def funcC(sigma, z):
27
64
135
8
18
ialireza13/Defect-Dynamics
functions.py
Python
funcC
funcC
5
15
5
5
e00e922668e081ec1a9593d21b35b13d62a3928d
bigcode/the-stack
train
fe247511e7c2718f18343167
train
function
def get_fixedpoint(args): ''' defects_loc, defects_charge, L, a, alpha, dt ''' defects_loc, defects_charge, L, a, alpha, dt = args z = np.zeros(len(defects_charge), dtype='complex128') for d in range(len(defects_loc)): z[d] = defects_loc[d][0]-defects_loc[d][1]*1j phis = np.ze...
def get_fixedpoint(args):
''' defects_loc, defects_charge, L, a, alpha, dt ''' defects_loc, defects_charge, L, a, alpha, dt = args z = np.zeros(len(defects_charge), dtype='complex128') for d in range(len(defects_loc)): z[d] = defects_loc[d][0]-defects_loc[d][1]*1j phis = np.zeros(len(defects_charge)) ...
phis[t_idx:,remaining_defs[0]] = phiss[:-1,:] break X = np.zeros(z.shape, dtype=float) Y = np.zeros(z.shape, dtype=float) Vx = np.zeros(z.shape, dtype=float) Vy = np.zeros(z.shape, dtype=float) for d in range(z.shape[1]): X[:,d] = np.real(z[:,d]) ...
154
154
515
6
147
ialireza13/Defect-Dynamics
functions.py
Python
get_fixedpoint
get_fixedpoint
153
202
153
153
9d5bafaed9d0296319fd45dddbbb3091815a76b2
bigcode/the-stack
train
1aeb98fe2ba85220922c7a76
train
function
def funceiphi(sigma, z, psi): eiphi = np.ones(len(z), dtype='complex128') for i in range(len(z)): for j in range(len(z)): if i!=j: eiphi[i]*= np.power((z[i]-z[j])/(np.conj(z[i])-np.conj(z[j])), sigma[j]) * np.exp(2*1j*psi[i]) # z_ = np.conj(z) # eiphi = np.power((np.o...
def funceiphi(sigma, z, psi):
eiphi = np.ones(len(z), dtype='complex128') for i in range(len(z)): for j in range(len(z)): if i!=j: eiphi[i]*= np.power((z[i]-z[j])/(np.conj(z[i])-np.conj(z[j])), sigma[j]) * np.exp(2*1j*psi[i]) # z_ = np.conj(z) # eiphi = np.power((np.outer(z,np.ones(z.shape)) - np....
5)/(4.0*a) SR = eiphi*(sigma==0.5)/(4.0*a) return SR def funcpsi(sigma,z): psi = np.power(z/np.conj(z), sigma) return psi def funceiphi(sigma, z, psi):
64
64
209
11
52
ialireza13/Defect-Dynamics
functions.py
Python
funceiphi
funceiphi
28
39
28
28
9d26bbd7ec9e17233c8439933db63fa62d9696cb
bigcode/the-stack
train
38ccc7e78b93d82764154a27
train
function
def get_trajectory(args): ''' defects_loc, defects_charge, L, a, alpha, tMax, dt = args ''' defects_loc, defects_charge, L, a, alpha, tMax, dt = args times = np.arange(start=0, step=dt, stop=tMax) z = np.zeros((len(times), len(defects_charge)), dtype='complex128') zdots = np.zeros((len(time...
def get_trajectory(args):
''' defects_loc, defects_charge, L, a, alpha, tMax, dt = args ''' defects_loc, defects_charge, L, a, alpha, tMax, dt = args times = np.arange(start=0, step=dt, stop=tMax) z = np.zeros((len(times), len(defects_charge)), dtype='complex128') zdots = np.zeros((len(times), len(defects_charge)), ...
complex128') for i in range(len(z)): for j in range(len(z)): if i!=j: B[i,j] = sigma[i]*sigma[j] * np.log(L/np.abs(z[i]-z[j])) continue B[i,j] = sigma[i]*sigma[j] * np.log(L/a) # B = np.outer(sigma,sigma)*np.log(L/np.abs(np.outer(z,np.ones(z.shape)...
256
256
903
6
249
ialireza13/Defect-Dynamics
functions.py
Python
get_trajectory
get_trajectory
84
151
84
84
39b94bfe73a702e5b08df750d0639bec82924f8f
bigcode/the-stack
train
7b53028cbff737f130b5a0b5
train
function
def get_first_collision(args): ''' defects_loc, defects_charge, L, a, alpha, dt, alt_t = args ''' defects_loc, defects_charge, L, a, alpha, dt, alt_t = args z = np.zeros(len(defects_charge), dtype='complex128') for d in range(len(defects_loc)): z[d] = defects_loc[d][0]-defects_loc[d][1]...
def get_first_collision(args):
''' defects_loc, defects_charge, L, a, alpha, dt, alt_t = args ''' defects_loc, defects_charge, L, a, alpha, dt, alt_t = args z = np.zeros(len(defects_charge), dtype='complex128') for d in range(len(defects_loc)): z[d] = defects_loc[d][0]-defects_loc[d][1]*1j defects_loc = np.a...
for d in remaining_defs[0]: defects_loc_.append([np.real(z[d]), -np.imag(z[d])]) x,y = get_fixedpoint((defects_loc_, defects_charge[remaining_defs[0]], L, a, alpha, dt)) z[remaining_defs[0]] = x[:]-y[:]*1j break X[:] = np.real(z[:]) ...
108
108
363
6
101
ialireza13/Defect-Dynamics
functions.py
Python
get_first_collision
get_first_collision
204
239
204
204
146decb55de2f901a9c7e27f038e56f9418a1d4d
bigcode/the-stack
train
814bd50e8d36bb290166be8f
train
function
def convert_tensor_encoding( tensor: torch.tensor, dtype: torch.dtype, ): """Convert input tensor with values between -1 and 1 to integer encoding Args: tensor: input tensor, assumed between -1 and 1 dtype: desired output tensor dtype Returns: Tensor: shape of (n_channels, sa...
def convert_tensor_encoding( tensor: torch.tensor, dtype: torch.dtype, ):
"""Convert input tensor with values between -1 and 1 to integer encoding Args: tensor: input tensor, assumed between -1 and 1 dtype: desired output tensor dtype Returns: Tensor: shape of (n_channels, sample_rate * duration) """ if dtype == torch.int32: tensor *= (tens...
os.path.join(os.path.dirname(__file__), '..')) def get_asset_path(*paths): """Return full path of a test asset""" return os.path.join(_TEST_DIR_PATH, 'assets', *paths) def convert_tensor_encoding( tensor: torch.tensor, dtype: torch.dtype, ):
64
64
197
18
46
adefossez/audio
test/torchaudio_unittest/common_utils/data_utils.py
Python
convert_tensor_encoding
convert_tensor_encoding
16
35
16
19
10acca9945c10713831a1bd01b063f1719e11de0
bigcode/the-stack
train
7ab5880a48d934e3f416bc33
train
function
def get_asset_path(*paths): """Return full path of a test asset""" return os.path.join(_TEST_DIR_PATH, 'assets', *paths)
def get_asset_path(*paths):
"""Return full path of a test asset""" return os.path.join(_TEST_DIR_PATH, 'assets', *paths)
import os.path from typing import Union import torch _TEST_DIR_PATH = os.path.realpath( os.path.join(os.path.dirname(__file__), '..')) def get_asset_path(*paths):
40
64
33
7
33
adefossez/audio
test/torchaudio_unittest/common_utils/data_utils.py
Python
get_asset_path
get_asset_path
11
13
11
11
6ca788acc1c5968dec128c7985884b3f1e512c12
bigcode/the-stack
train
86d721003145e7b132745502
train
function
def get_whitenoise( *, sample_rate: int = 16000, duration: float = 1, # seconds n_channels: int = 1, seed: int = 0, dtype: Union[str, torch.dtype] = "float32", device: Union[str, torch.device] = "cpu", channels_first=True, scale_factor: float = 1, ): """Generate pseudo audio dat...
def get_whitenoise( *, sample_rate: int = 16000, duration: float = 1, # seconds n_channels: int = 1, seed: int = 0, dtype: Union[str, torch.dtype] = "float32", device: Union[str, torch.device] = "cpu", channels_first=True, scale_factor: float = 1, ):
"""Generate pseudo audio data with whitenoise Args: sample_rate: Sampling rate duration: Length of the resulting Tensor in seconds. n_channels: Number of channels seed: Seed value used for random number generation. Note that this function does not modify global random...
* 127 + (tensor < 0) * 128 tensor += 128 tensor = tensor.to(dtype) return tensor def get_whitenoise( *, sample_rate: int = 16000, duration: float = 1, # seconds n_channels: int = 1, seed: int = 0, dtype: Union[str, torch.dtype] = "float32", device: Union[str, torch.device] ...
120
120
402
89
30
adefossez/audio
test/torchaudio_unittest/common_utils/data_utils.py
Python
get_whitenoise
get_whitenoise
38
78
38
48
560bffa186a87f404b7547f97fc3fd655763a308
bigcode/the-stack
train
6d12114e6f68dc7fc7da3717
train
function
def get_sinusoid( *, frequency: float = 300, sample_rate: int = 16000, duration: float = 1, # seconds n_channels: int = 1, dtype: Union[str, torch.dtype] = "float32", device: Union[str, torch.device] = "cpu", channels_first: bool = True, ): """Generate pseudo audio data with sine wa...
def get_sinusoid( *, frequency: float = 300, sample_rate: int = 16000, duration: float = 1, # seconds n_channels: int = 1, dtype: Union[str, torch.dtype] = "float32", device: Union[str, torch.device] = "cpu", channels_first: bool = True, ):
"""Generate pseudo audio data with sine wave. Args: frequency: Frequency of sine wave sample_rate: Sampling rate duration: Length of the resulting Tensor in seconds. n_channels: Number of channels dtype: Torch dtype device: device Returns: Tensor: sh...
def get_sinusoid( *, frequency: float = 300, sample_rate: int = 16000, duration: float = 1, # seconds n_channels: int = 1, dtype: Union[str, torch.dtype] = "float32", device: Union[str, torch.device] = "cpu", channels_first: bool = True, ):
83
79
265
83
0
adefossez/audio
test/torchaudio_unittest/common_utils/data_utils.py
Python
get_sinusoid
get_sinusoid
81
112
81
90
07b563e503faa474c4e6fcb28e98f7c81b667137
bigcode/the-stack
train
19b26039bdcc72f0ff74ad4f
train
function
def glorot_normal(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable: """Builds a Glorot normal initializer (aka Xavier normal initializer). A `Glorot normal ...
def glorot_normal(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable:
"""Builds a Glorot normal initializer (aka Xavier normal initializer). A `Glorot normal initializer`_ is a specialization of :func:`jax.nn.initializers.variance_scaling` where ``scale = 1.0``, ``mode="fan_avg"``, and ``distribution="truncated_normal"``. Args: in_axis: axis or sequence of axes of the inp...
proceedings.mlr.press/v9/glorot10a.html """ return variance_scaling(1.0, "fan_avg", "uniform", in_axis=in_axis, out_axis=out_axis, batch_axis=batch_axis, dtype=dtype) xavier_uniform = glorot_uniform def glorot_normal(in_axis: Union[int, Sequence[int]] = -2, out_axis: Uni...
116
116
387
53
62
mariogeiger/jax
jax/_src/nn/initializers.py
Python
glorot_normal
glorot_normal
286
319
286
289
4146663ccdc58196154fe2893373776f2e49c748
bigcode/the-stack
train
7e2bc64809aabb4395504546
train
function
def lecun_uniform(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable: """Builds a Lecun uniform initializer. A `Lecun uniform initializer`_ is a specializatio...
def lecun_uniform(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable:
"""Builds a Lecun uniform initializer. A `Lecun uniform initializer`_ is a specialization of :func:`jax.nn.initializers.variance_scaling` where ``scale = 1.0``, ``mode="fan_in"``, and ``distribution="uniform"``. Args: in_axis: axis or sequence of axes of the input dimension in the weights array. ...
9/glorot10a.html """ return variance_scaling(1.0, "fan_avg", "truncated_normal", in_axis=in_axis, out_axis=out_axis, batch_axis=batch_axis, dtype=dtype) xavier_normal = glorot_normal def lecun_uniform(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence...
111
111
373
53
57
mariogeiger/jax
jax/_src/nn/initializers.py
Python
lecun_uniform
lecun_uniform
323
356
323
326
a1fd3aa652c68c613783e30248dfd1ff367e2add
bigcode/the-stack
train
2cded97a05fa863187e1599c
train
function
def he_normal(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable: """Builds a He normal initializer (aka Kaiming normal initializer). A `He normal initializer`_ is a spec...
def he_normal(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable:
"""Builds a He normal initializer (aka Kaiming normal initializer). A `He normal initializer`_ is a specialization of :func:`jax.nn.initializers.variance_scaling` where ``scale = 2.0``, ``mode="fan_in"``, and ``distribution="truncated_normal"``. Args: in_axis: axis or sequence of axes of the input dimen...
: https://arxiv.org/abs/1502.01852 """ return variance_scaling(2.0, "fan_in", "uniform", in_axis=in_axis, out_axis=out_axis, batch_axis=batch_axis, dtype=dtype) kaiming_uniform = he_uniform def he_normal(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[...
114
114
380
52
61
mariogeiger/jax
jax/_src/nn/initializers.py
Python
he_normal
he_normal
432
465
432
435
8f2a2c9cbcab613bb25e41bf42f6bb50b523d40e
bigcode/the-stack
train
0ad19588c18e9979b9b917cb
train
function
def ones(key, shape, dtype: DType = jnp.float_): """An initializer that returns a constant array full of ones. The ``key`` argument is ignored. >>> import jax, jax.numpy as jnp >>> jax.nn.initializers.ones(jax.random.PRNGKey(42), (3, 2), jnp.float32) DeviceArray([[1., 1.], [1., 1.], ...
def ones(key, shape, dtype: DType = jnp.float_):
"""An initializer that returns a constant array full of ones. The ``key`` argument is ignored. >>> import jax, jax.numpy as jnp >>> jax.nn.initializers.ones(jax.random.PRNGKey(42), (3, 2), jnp.float32) DeviceArray([[1., 1.], [1., 1.], [1., 1.]], dtype=float32) """ return jn...
.float32) DeviceArray([[0., 0., 0.], [0., 0., 0.]], dtype=float32) """ return jnp.zeros(shape, dtypes.canonicalize_dtype(dtype)) def ones(key, shape, dtype: DType = jnp.float_):
64
64
126
16
48
mariogeiger/jax
jax/_src/nn/initializers.py
Python
ones
ones
46
57
46
46
6312632955f4b70083121e6f2496c2be7bceae2a
bigcode/the-stack
train
3d9ff6dc1b27534bd6d8cef8
train
function
def constant(value, dtype: DType = jnp.float_) -> Callable: """Builds an initializer that returns arrays full of a constant ``value``. Args: value: the constant value with which to fill the initializer. dtype: optional; the initializer's default dtype. >>> import jax, jax.numpy as jnp >>> initializer ...
def constant(value, dtype: DType = jnp.float_) -> Callable:
"""Builds an initializer that returns arrays full of a constant ``value``. Args: value: the constant value with which to fill the initializer. dtype: optional; the initializer's default dtype. >>> import jax, jax.numpy as jnp >>> initializer = jax.nn.initializers.constant(-7) >>> initializer(jax.ran...
) DeviceArray([[1., 1.], [1., 1.], [1., 1.]], dtype=float32) """ return jnp.ones(shape, dtypes.canonicalize_dtype(dtype)) def constant(value, dtype: DType = jnp.float_) -> Callable:
64
64
178
16
48
mariogeiger/jax
jax/_src/nn/initializers.py
Python
constant
constant
59
75
59
59
079bf9e37c8ef937b27108898591b45dc2e62449
bigcode/the-stack
train
7187312d00b1c87b580c163f
train
function
def glorot_uniform(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable: """Builds a Glorot uniform initializer (aka Xavier uniform initializer). A `Glorot u...
def glorot_uniform(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable:
"""Builds a Glorot uniform initializer (aka Xavier uniform initializer). A `Glorot uniform initializer`_ is a specialization of :func:`jax.nn.initializers.variance_scaling` where ``scale = 1.0``, ``mode="fan_avg"``, and ``distribution="uniform"``. Args: in_axis: axis or sequence of axes of the input dim...
, shape, dtype, -1) * jnp.sqrt(3 * variance) else: return _complex_uniform(key, shape, dtype) * jnp.sqrt(variance) else: raise ValueError(f"invalid distribution for variance scaling initializer: {distribution}") return init def glorot_uniform(in_axis: Union[int, Sequence[int]] = -2, ...
114
114
383
53
60
mariogeiger/jax
jax/_src/nn/initializers.py
Python
glorot_uniform
glorot_uniform
248
281
248
251
b71f046eecbce25909161ff0727ebdcda4815324
bigcode/the-stack
train
f5c207d61fda46b7022bb09a
train
function
def _compute_fans(shape: core.NamedShape, in_axis=-2, out_axis=-1, batch_axis=()): """ Compute effective input and output sizes for a linear or convolutional layer. Axes not in in_axis, out_axis, or batch_axis are assumed to constitute the "receptive field" of a convolution (kernel spatial di...
def _compute_fans(shape: core.NamedShape, in_axis=-2, out_axis=-1, batch_axis=()):
""" Compute effective input and output sizes for a linear or convolutional layer. Axes not in in_axis, out_axis, or batch_axis are assumed to constitute the "receptive field" of a convolution (kernel spatial dimensions). """ if isinstance(in_axis, int): in_size = shape[in_axis] else: in_size = in...
32) """ def init(key, shape, dtype=dtype): dtype = dtypes.canonicalize_dtype(dtype) return random.normal(key, shape, dtype) * stddev return init def _compute_fans(shape: core.NamedShape, in_axis=-2, out_axis=-1, batch_axis=()):
70
70
236
26
43
mariogeiger/jax
jax/_src/nn/initializers.py
Python
_compute_fans
_compute_fans
121
144
121
122
56b45903ad76f126082e8f0ba3110aceb50a1fd3
bigcode/the-stack
train
8fe39194b9fda7072f86c414
train
function
def orthogonal(scale=1.0, column_axis=-1, dtype: DType = jnp.float_): """ Builds an initializer that returns uniformly distributed orthogonal matrices. If the shape is not square, the matrices will have orthonormal rows or columns depending on which side is smaller. Args: scale: the upper bound of the u...
def orthogonal(scale=1.0, column_axis=-1, dtype: DType = jnp.float_):
""" Builds an initializer that returns uniformly distributed orthogonal matrices. If the shape is not square, the matrices will have orthonormal rows or columns depending on which side is smaller. Args: scale: the upper bound of the uniform distribution. column_axis: the axis that contains the colum...
1.1900088 , 1.2047218 ], [-0.87225807, -0.95321447, 0.1369438 ]], dtype=float32) .. _He normal initializer: https://arxiv.org/abs/1502.01852 """ return variance_scaling(2.0, "fan_in", "truncated_normal", in_axis=in_axis, out_axis=out_axis, batch_axis=batch_axis, dtype...
138
138
461
24
113
mariogeiger/jax
jax/_src/nn/initializers.py
Python
orthogonal
orthogonal
470
507
470
470
fb1a2950995b796983a232b588d93de1aed7ae84
bigcode/the-stack
train
2b1c838577be330ecb0d3221
train
function
def normal(stddev=1e-2, dtype: DType = jnp.float_) -> Callable: """Builds an initializer that returns real normally-distributed random arrays. Args: stddev: optional; the standard deviation of the distribution. dtype: optional; the initializer's default dtype. Returns: An initializer that returns ar...
def normal(stddev=1e-2, dtype: DType = jnp.float_) -> Callable:
"""Builds an initializer that returns real normally-distributed random arrays. Args: stddev: optional; the standard deviation of the distribution. dtype: optional; the initializer's default dtype. Returns: An initializer that returns arrays whose values are normally distributed with mean ``0`` a...
5.5022564]], dtype=float32) """ def init(key, shape, dtype=dtype): dtype = dtypes.canonicalize_dtype(dtype) return random.uniform(key, shape, dtype) * scale return init def normal(stddev=1e-2, dtype: DType = jnp.float_) -> Callable:
74
74
248
22
51
mariogeiger/jax
jax/_src/nn/initializers.py
Python
normal
normal
99
119
99
99
c52a53c162af8b7b043a50c0b535ed19d7b1909b
bigcode/the-stack
train
bde85f8fe1aad1be837c192b
train
function
def delta_orthogonal(scale=1.0, column_axis=-1, dtype: DType = jnp.float_): """ Builds an initializer for delta orthogonal kernels. Args: scale: the upper bound of the uniform distribution. column_axis: the axis that contains the columns that should be orthogonal. dtype: the default dtype of the weig...
def delta_orthogonal(scale=1.0, column_axis=-1, dtype: DType = jnp.float_):
""" Builds an initializer for delta orthogonal kernels. Args: scale: the upper bound of the uniform distribution. column_axis: the axis that contains the columns that should be orthogonal. dtype: the default dtype of the weights. Returns: A `delta orthogonal initializer`_. The shape passed to ...
raise ValueError("orthogonal initializer requires at least a 2D shape") n_rows, n_cols = prod(shape) // shape[column_axis], shape[column_axis] matrix_shape = (n_cols, n_rows) if n_rows < n_cols else (n_rows, n_cols) A = random.normal(key, matrix_shape, dtype) Q, R = jnp.linalg.qr(A) diag_sign ...
207
207
691
26
180
mariogeiger/jax
jax/_src/nn/initializers.py
Python
delta_orthogonal
delta_orthogonal
510
562
510
510
fa7b340343a07670d7877df09c8f011edcb0a64d
bigcode/the-stack
train
93959183a0b9de365c9041d8
train
function
def _complex_uniform(key, shape, dtype): """ Sample uniform random values within a disk on the complex plane, with zero mean and unit variance. """ key_r, key_theta = random.split(key) dtype = np.array(0, dtype).real.dtype r = jnp.sqrt(2 * random.uniform(key_r, shape, dtype)) theta = 2 * jnp.pi * random...
def _complex_uniform(key, shape, dtype):
""" Sample uniform random values within a disk on the complex plane, with zero mean and unit variance. """ key_r, key_theta = random.split(key) dtype = np.array(0, dtype).real.dtype r = jnp.sqrt(2 * random.uniform(key_r, shape, dtype)) theta = 2 * jnp.pi * random.uniform(key_theta, shape, dtype) retur...
] for i in batch_axis])) receptive_field_size = shape.total / in_size / out_size / batch_size fan_in = in_size * receptive_field_size fan_out = out_size * receptive_field_size return fan_in, fan_out def _complex_uniform(key, shape, dtype):
64
64
109
10
53
mariogeiger/jax
jax/_src/nn/initializers.py
Python
_complex_uniform
_complex_uniform
146
155
146
146
40e827d44a9ff5a28e028b92818f4c13a27459f3
bigcode/the-stack
train
7376608854bd71ca152de5d0
train
function
def he_uniform(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable: """Builds a He uniform initializer (aka Kaiming uniform initializer). A `He uniform initializer`_ is...
def he_uniform(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable:
"""Builds a He uniform initializer (aka Kaiming uniform initializer). A `He uniform initializer`_ is a specialization of :func:`jax.nn.initializers.variance_scaling` where ``scale = 2.0``, ``mode="fan_in"``, and ``distribution="uniform"``. Args: in_axis: axis or sequence of axes of the input dimension i...
un normal initializer: https://arxiv.org/abs/1706.02515 """ return variance_scaling(1.0, "fan_in", "truncated_normal", in_axis=in_axis, out_axis=out_axis, batch_axis=batch_axis, dtype=dtype) def he_uniform(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequenc...
112
112
375
52
60
mariogeiger/jax
jax/_src/nn/initializers.py
Python
he_uniform
he_uniform
394
427
394
397
c08bb6fa0cf3bb4fe1f99ca47b73b84b6597edcf
bigcode/the-stack
train
731e9de08d4006b8e3ce964e
train
function
def lecun_normal(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable: """Builds a Lecun normal initializer. A `Lecun normal initializer`_ is a specialization of ...
def lecun_normal(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable:
"""Builds a Lecun normal initializer. A `Lecun normal initializer`_ is a specialization of :func:`jax.nn.initializers.variance_scaling` where ``scale = 1.0``, ``mode="fan_in"``, and ``distribution="truncated_normal"``. Args: in_axis: axis or sequence of axes of the input dimension in the weights a...
Lecun uniform initializer: https://arxiv.org/abs/1706.02515 """ return variance_scaling(1.0, "fan_in", "uniform", in_axis=in_axis, out_axis=out_axis, batch_axis=batch_axis, dtype=dtype) def lecun_normal(in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence...
113
113
377
53
60
mariogeiger/jax
jax/_src/nn/initializers.py
Python
lecun_normal
lecun_normal
358
391
358
361
4e4b55d0635f9fe8d3782e99d4634d55633a7983
bigcode/the-stack
train
679a0295e08fe4b1028dea85
train
function
def variance_scaling(scale, mode: str, distribution: str, in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable: r""" Initializer th...
def variance_scaling(scale, mode: str, distribution: str, in_axis: Union[int, Sequence[int]] = -2, out_axis: Union[int, Sequence[int]] = -1, batch_axis: Sequence[int] = (), dtype: DType = jnp.float_) -> Callable:
r""" Initializer that adapts its scale to the shape of the weights tensor. With ``distribution="truncated_normal"`` or ``distribution="normal"``, samples are drawn from a (truncated) normal distribution with a mean of zero and a standard deviation (after truncation, if applicable) of :math:`\sqrt{\frac{sca...
.uniform(key_r, shape, dtype)) theta = 2 * jnp.pi * random.uniform(key_theta, shape, dtype) return r * jnp.exp(1j * theta) def _complex_truncated_normal(key, upper, shape, dtype): """ Sample random values from a centered normal distribution on the complex plane, whose modulus is truncated to `upper`, and the...
256
256
895
64
192
mariogeiger/jax
jax/_src/nn/initializers.py
Python
variance_scaling
variance_scaling
169
246
169
173
62e3e389edf1f13ecde6390ce1d8a2a24b078ae3
bigcode/the-stack
train
9402c672c082923fbb9196a2
train
function
def _complex_truncated_normal(key, upper, shape, dtype): """ Sample random values from a centered normal distribution on the complex plane, whose modulus is truncated to `upper`, and the variance before the truncation is one. """ key_r, key_theta = random.split(key) dtype = np.array(0, dtype).real.dtype t...
def _complex_truncated_normal(key, upper, shape, dtype):
""" Sample random values from a centered normal distribution on the complex plane, whose modulus is truncated to `upper`, and the variance before the truncation is one. """ key_r, key_theta = random.split(key) dtype = np.array(0, dtype).real.dtype t = (1 - jnp.exp(jnp.array(-(upper ** 2), dtype))) * rando...
r = jnp.sqrt(2 * random.uniform(key_r, shape, dtype)) theta = 2 * jnp.pi * random.uniform(key_theta, shape, dtype) return r * jnp.exp(1j * theta) def _complex_truncated_normal(key, upper, shape, dtype):
64
64
152
14
50
mariogeiger/jax
jax/_src/nn/initializers.py
Python
_complex_truncated_normal
_complex_truncated_normal
157
167
157
157
79a197a6664a41e7817428da2d8a34c2c1d8424a
bigcode/the-stack
train
f828cfdd91d68403189a84c2
train
function
def zeros(key, shape, dtype: DType = jnp.float_): """An initializer that returns a constant array full of zeros. The ``key`` argument is ignored. >>> import jax, jax.numpy as jnp >>> jax.nn.initializers.zeros(jax.random.PRNGKey(42), (2, 3), jnp.float32) DeviceArray([[0., 0., 0.], [0., 0., 0.]...
def zeros(key, shape, dtype: DType = jnp.float_):
"""An initializer that returns a constant array full of zeros. The ``key`` argument is ignored. >>> import jax, jax.numpy as jnp >>> jax.nn.initializers.zeros(jax.random.PRNGKey(42), (2, 3), jnp.float32) DeviceArray([[0., 0., 0.], [0., 0., 0.]], dtype=float32) """ return jnp.zeros(shape, ...
import jax.numpy as jnp from jax import lax from jax import random from jax import core from jax._src.util import prod from jax import dtypes DType = Any def zeros(key, shape, dtype: DType = jnp.float_):
64
64
124
16
47
mariogeiger/jax
jax/_src/nn/initializers.py
Python
zeros
zeros
34
44
34
34
2d79ddc5e5ca387de9fbe604bad0b9885e43173a
bigcode/the-stack
train
f102ecd6ac9bee0b81c0bfca
train
function
def uniform(scale=1e-2, dtype: DType = jnp.float_) -> Callable: """Builds an initializer that returns real uniformly-distributed random arrays. Args: scale: optional; the upper bound of the random distribution. dtype: optional; the initializer's default dtype. Returns: An initializer that returns ar...
def uniform(scale=1e-2, dtype: DType = jnp.float_) -> Callable:
"""Builds an initializer that returns real uniformly-distributed random arrays. Args: scale: optional; the upper bound of the random distribution. dtype: optional; the initializer's default dtype. Returns: An initializer that returns arrays whose values are uniformly distributed in the range ``[...
., -7.]], dtype=float32) """ def init(key, shape, dtype=dtype): dtype = dtypes.canonicalize_dtype(dtype) return jnp.full(shape, value, dtype=dtype) return init def uniform(scale=1e-2, dtype: DType = jnp.float_) -> Callable:
71
71
238
21
49
mariogeiger/jax
jax/_src/nn/initializers.py
Python
uniform
uniform
77
97
77
77
e26d69a319cea11980efe586563757f9468dd72f
bigcode/the-stack
train
def738ef07a8031950a1f0b3
train
class
class LevenshteinTransformerDecoder(TracingTransformerDecoder): def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False): super().__init__( args, dictionary, embed_tokens, no_encoder_attn=no_encoder_attn ) self.dictionary = dictionary self.bos = dic...
class LevenshteinTransformerDecoder(TracingTransformerDecoder):
def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False): super().__init__( args, dictionary, embed_tokens, no_encoder_attn=no_encoder_attn ) self.dictionary = dictionary self.bos = dictionary.bos() self.unk = dictionary.unk() self....
return x if x.size()[0] == 0 else x[:, :l, :] output_tokens = slice_wrap(output_tokens, cut_off) output_scores = slice_wrap(output_scores, cut_off) attn = slice_wrap(attn, cut_off) return [output_tokens, output_scores, attn, 0, 0] def initialize_output_tokens(sel...
255
256
1,036
12
243
skeshaw/LoReNMT
fairseq/models/levenshtein_transformer.py
Python
LevenshteinTransformerDecoder
LevenshteinTransformerDecoder
511
642
511
511
ef23cbb39c9c547d6e25f2ef943f74cc1b9d8c0e
bigcode/the-stack
train
d8854358143ef6b72fe39290
train
function
@register_model_architecture( "levenshtein_transformer", "levenshtein_transformer_wmt_en_de_big" ) def levenshtein_transformer_wmt_en_de_big_t2t(args): args.encoder_normalize_before = getattr(args, "encoder_normalize_before", True) args.decoder_normalize_before = getattr(args, "decoder_normalize_before...
@register_model_architecture( "levenshtein_transformer", "levenshtein_transformer_wmt_en_de_big" ) def levenshtein_transformer_wmt_en_de_big_t2t(args):
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", True) args.decoder_normalize_before = getattr(args, "decoder_normalize_before", True) args.attention_dropout = getattr(args, "attention_dropout", 0.1) args.activation_dropout = getattr(args, "activation_dropout", 0.1) leve...
.3) base_architecture(args) # default parameters used in tensor2tensor implementation @register_model_architecture( "levenshtein_transformer", "levenshtein_transformer_wmt_en_de_big" ) def levenshtein_transformer_wmt_en_de_big_t2t(args):
64
64
132
45
18
skeshaw/LoReNMT
fairseq/models/levenshtein_transformer.py
Python
levenshtein_transformer_wmt_en_de_big_t2t
levenshtein_transformer_wmt_en_de_big_t2t
713
721
713
716
0410c765663b85bf71e4ba36928b90ff86979223
bigcode/the-stack
train
9e1ae8512b63881e653812fb
train
class
@register_model("levenshtein_transformer") class LevenshteinTransformerModel(TracingTransformerModel): def __init__(self, encoder, decoder): super().__init__(encoder, decoder) self.tgt_dict = decoder.dictionary self.bos = decoder.dictionary.bos() self.eos = decoder.dictionary.e...
@register_model("levenshtein_transformer") class LevenshteinTransformerModel(TracingTransformerModel):
def __init__(self, encoder, decoder): super().__init__(encoder, decoder) self.tgt_dict = decoder.dictionary self.bos = decoder.dictionary.bos() self.eos = decoder.dictionary.eos() self.pad = decoder.dictionary.pad() self.unk = decoder.dictionary.unk() @st...
] out_tokens_list = [ [t for t in s if t != padding_idx] for i, s in enumerate(out_tokens.tolist()) ] full_labels = libnat.suggested_ed2_path( in_tokens_list, out_tokens_list, padding_idx ) word_del_targets = [b[-1] for b in full_labels] word_del_targets = [ ...
256
256
3,016
23
232
skeshaw/LoReNMT
fairseq/models/levenshtein_transformer.py
Python
LevenshteinTransformerModel
LevenshteinTransformerModel
152
508
152
153
8c108889248b5844c6ec01f23dc035c4792f373b
bigcode/the-stack
train
bbc52af992d0f2d64c72964e
train
function
@register_model_architecture("levenshtein_transformer", "levenshtein_transformer") def base_architecture(args): args.encoder_embed_path = getattr(args, "encoder_embed_path", None) args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512) args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_emb...
@register_model_architecture("levenshtein_transformer", "levenshtein_transformer") def base_architecture(args):
args.encoder_embed_path = getattr(args, "encoder_embed_path", None) args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512) args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048) args.encoder_layers = getattr(args, "encoder_layers", 6) args.encoder_attention_heads = g...
attn def forward_word_ins(self, prev_output_tokens, encoder_out=None, **unused): features, attn, _ = self.extract_features( prev_output_tokens, encoder_out=encoder_out, early_exit=self.early_exit[2], layers=self.layers, **unused ...
182
182
609
27
154
skeshaw/LoReNMT
fairseq/models/levenshtein_transformer.py
Python
base_architecture
base_architecture
645
686
645
646
af76b52f6b4686613aa16dbc26e3fc65addcd13d
bigcode/the-stack
train
a1f129ab25058653daacb7f7
train
function
def _get_del_targets(in_tokens, out_tokens, padding_idx): try: from fairseq import libnat except ImportError as e: import sys sys.stderr.write("ERROR: missing libnat. run `pip install --editable .`\n") raise e out_seq_len = out_tokens.size(1) in_tokens_list = ...
def _get_del_targets(in_tokens, out_tokens, padding_idx):
try: from fairseq import libnat except ImportError as e: import sys sys.stderr.write("ERROR: missing libnat. run `pip install --editable .`\n") raise e out_seq_len = out_tokens.size(1) in_tokens_list = [ [t for t in s if t != padding_idx] for i, s in e...
.device).bool() mask_ins_targets = torch.tensor(mask_ins_targets, device=in_tokens.device) masked_tgt_tokens = out_tokens.masked_fill(masked_tgt_masks, unk_idx) return masked_tgt_masks, masked_tgt_tokens, mask_ins_targets def _get_del_targets(in_tokens, out_tokens, padding_idx):
70
70
235
14
55
skeshaw/LoReNMT
fairseq/models/levenshtein_transformer.py
Python
_get_del_targets
_get_del_targets
80
108
80
80
59a2b80581e8344494cbd799a3fa1429c27ff0e9
bigcode/the-stack
train
149df70e645368a0d0a8d7df
train
function
def _get_del_ins_targets(in_tokens, out_tokens, padding_idx): try: from fairseq import libnat except ImportError as e: import sys sys.stderr.write("ERROR: missing libnat. run `pip install --editable .`\n") raise e in_seq_len, out_seq_len = in_tokens.size(1), out_toke...
def _get_del_ins_targets(in_tokens, out_tokens, padding_idx):
try: from fairseq import libnat except ImportError as e: import sys sys.stderr.write("ERROR: missing libnat. run `pip install --editable .`\n") raise e in_seq_len, out_seq_len = in_tokens.size(1), out_tokens.size(1) in_tokens_list = [ [t for t in s if ...
( in_tokens_list, out_tokens_list, padding_idx ) word_del_targets = [b[-1] for b in full_labels] word_del_targets = [ labels + [0 for _ in range(out_seq_len - len(labels))] for labels in word_del_targets ] # transform to tensor word_del_targets = torch.tensor(w...
103
103
345
15
87
skeshaw/LoReNMT
fairseq/models/levenshtein_transformer.py
Python
_get_del_ins_targets
_get_del_ins_targets
111
149
111
111
dc20c4cab461889e5f8bfe7d71b4c387a438f194
bigcode/the-stack
train
8db786c389e56f987d43141d
train
function
def _get_ins_targets(in_tokens, out_tokens, padding_idx, unk_idx): try: from fairseq import libnat except ImportError as e: import sys sys.stderr.write("ERROR: missing libnat. run `pip install --editable .`\n") raise e in_seq_len, out_seq_len = in_tokens.size(1), out...
def _get_ins_targets(in_tokens, out_tokens, padding_idx, unk_idx):
try: from fairseq import libnat except ImportError as e: import sys sys.stderr.write("ERROR: missing libnat. run `pip install --editable .`\n") raise e in_seq_len, out_seq_len = in_tokens.size(1), out_tokens.size(1) in_tokens_list = [ [t for t in s if ...
torch.nn.functional as F from fairseq.models import register_model, register_model_architecture from fairseq.models.tracing_compliant_transformer import ( TracingTransformerDecoder, TracingTransformerEncoder, TracingTransformerModel, TransformerDecoderLayer, ) from fairseq.models.model_utils im...
129
129
432
17
111
skeshaw/LoReNMT
fairseq/models/levenshtein_transformer.py
Python
_get_ins_targets
_get_ins_targets
35
77
35
35
d7a5f3e73bcc3a3daaf2cbebe80c73b67bd41ecc
bigcode/the-stack
train
827ffc7dabe94b329b186026
train
function
@register_model_architecture( "levenshtein_transformer", "levenshtein_transformer_wmt_en_de" ) def levenshtein_transformer_wmt_en_de(args): base_architecture(args)
@register_model_architecture( "levenshtein_transformer", "levenshtein_transformer_wmt_en_de" ) def levenshtein_transformer_wmt_en_de(args):
base_architecture(args)
criminator", False) args.no_share_maskpredictor = getattr(args, "no_share_maskpredictor", False) @register_model_architecture( "levenshtein_transformer", "levenshtein_transformer_wmt_en_de" ) def levenshtein_transformer_wmt_en_de(args):
64
64
46
40
24
skeshaw/LoReNMT
fairseq/models/levenshtein_transformer.py
Python
levenshtein_transformer_wmt_en_de
levenshtein_transformer_wmt_en_de
689
693
689
692
082f78c532910139b53069da0d177c5273d8f64b
bigcode/the-stack
train
a59b0dc56f3bba57a658e228
train
function
@register_model_architecture( "levenshtein_transformer", "levenshtein_transformer_vaswani_wmt_en_de_big" ) def levenshtein_transformer_vaswani_wmt_en_de_big(args): args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1024) args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4096)...
@register_model_architecture( "levenshtein_transformer", "levenshtein_transformer_vaswani_wmt_en_de_big" ) def levenshtein_transformer_vaswani_wmt_en_de_big(args):
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1024) args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4096) args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 16) args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False) ...
All You Need" paper (Vaswani et al., 2017) @register_model_architecture( "levenshtein_transformer", "levenshtein_transformer_vaswani_wmt_en_de_big" ) def levenshtein_transformer_vaswani_wmt_en_de_big(args):
64
64
202
48
16
skeshaw/LoReNMT
fairseq/models/levenshtein_transformer.py
Python
levenshtein_transformer_vaswani_wmt_en_de_big
levenshtein_transformer_vaswani_wmt_en_de_big
697
709
697
700
86b837c38ffeedbcc8cfd1a898f79cc93a2fd966
bigcode/the-stack
train
8e28e25019458af5d8e988c5
train
function
def init_scalar_field(type): global Scalar Scalar = type global one one = Scalar(1) global zero zero = Scalar(0)
def init_scalar_field(type):
global Scalar Scalar = type global one one = Scalar(1) global zero zero = Scalar(0)
from __future__ import annotations one: Scalar = None zero: Scalar = None field_modulus = None Scalar = None def init_scalar_field(type):
35
64
37
6
28
oznurkalkar/polynom
polynom/ecc/__init__.py
Python
init_scalar_field
init_scalar_field
9
15
9
9
77ec0640b098f66ceb275da32b03f226f473b43f
bigcode/the-stack
train
4461af7460fad72ceffa1145
train
function
def init_ecc(curve: Curve): global CURVE CURVE = curve
def init_ecc(curve: Curve):
global CURVE CURVE = curve
pass class PairingFriendlyCurve(Curve): def is_pairing_friendly(self) -> bool: return True def pairing_check(self, pairs: list[tuple[Point, Point]]) -> bool: return self._pairing_check(pairs) def init_ecc(curve: Curve):
64
64
20
9
55
oznurkalkar/polynom
polynom/ecc/__init__.py
Python
init_ecc
init_ecc
60
62
60
60
fbf3091cfaadc5b543f9e5c8e13fad72d5d4b0b5
bigcode/the-stack
train
2c7366337210cca9144ef585
train
class
class Point(): @staticmethod def rand() -> Point: return Point.G1(Scalar.rand()) @staticmethod def ZERO(): return Point(CURVE, CURVE.z1) @staticmethod def G1(s: Scalar = one): p = Point(CURVE, CURVE.g1) if s is None: return p return p * s ...
class Point(): @staticmethod
def rand() -> Point: return Point.G1(Scalar.rand()) @staticmethod def ZERO(): return Point(CURVE, CURVE.z1) @staticmethod def G1(s: Scalar = one): p = Point(CURVE, CURVE.g1) if s is None: return p return p * s @staticmethod def G2(s: Sca...
def scalar_to_bytes(self, e: Scalar) -> bytes: pass class PairingFriendlyCurve(Curve): def is_pairing_friendly(self) -> bool: return True def pairing_check(self, pairs: list[tuple[Point, Point]]) -> bool: return self._pairing_check(pairs) def init_ecc(curve: Curve): globa...
136
136
455
7
129
oznurkalkar/polynom
polynom/ecc/__init__.py
Python
Point
Point
70
137
70
72
c27d1f0e9b7db4b6805f1a9fab6feaeaf95bfc87
bigcode/the-stack
train
d79a31798c54da16058948d1
train
function
def pairing_check(pairs: list[tuple[Point, Point]]) -> bool: assert CURVE.is_pairing_friendly() return CURVE.pairing_check(pairs)
def pairing_check(pairs: list[tuple[Point, Point]]) -> bool:
assert CURVE.is_pairing_friendly() return CURVE.pairing_check(pairs)
pairing_check(self, pairs: list[tuple[Point, Point]]) -> bool: return self._pairing_check(pairs) def init_ecc(curve: Curve): global CURVE CURVE = curve def pairing_check(pairs: list[tuple[Point, Point]]) -> bool:
64
64
38
17
46
oznurkalkar/polynom
polynom/ecc/__init__.py
Python
pairing_check
pairing_check
65
67
65
65
1dcf40128224546fdb5ac3dc140d4193ffeffc42
bigcode/the-stack
train
7d1c3baf2818d13ce1fc73f0
train
class
class Curve: def is_pairing_friendly(self): return False @staticmethod def uncompressed_point_size() -> int: pass @staticmethod def compressed_point_size() -> int: pass @staticmethod def scalar_size() -> int: pass def from_uncompressed(self, input: by...
class Curve:
def is_pairing_friendly(self): return False @staticmethod def uncompressed_point_size() -> int: pass @staticmethod def compressed_point_size() -> int: pass @staticmethod def scalar_size() -> int: pass def from_uncompressed(self, input: bytes): ...
zero: Scalar = None field_modulus = None Scalar = None def init_scalar_field(type): global Scalar Scalar = type global one one = Scalar(1) global zero zero = Scalar(0) CURVE: Curve = None class Curve:
64
64
126
3
60
oznurkalkar/polynom
polynom/ecc/__init__.py
Python
Curve
Curve
21
48
21
22
28440f7d91ab12f1b00c5fd6d5fc0654dbf96265
bigcode/the-stack
train
1460184638873ae99fa93a17
train
class
class PairingFriendlyCurve(Curve): def is_pairing_friendly(self) -> bool: return True def pairing_check(self, pairs: list[tuple[Point, Point]]) -> bool: return self._pairing_check(pairs)
class PairingFriendlyCurve(Curve):
def is_pairing_friendly(self) -> bool: return True def pairing_check(self, pairs: list[tuple[Point, Point]]) -> bool: return self._pairing_check(pairs)
, input: bytes): pass def to_uncompressed(self, p: Point) -> bytes: pass def scalar_from_bytes(self, input: bytes): pass def scalar_to_bytes(self, e: Scalar) -> bytes: pass class PairingFriendlyCurve(Curve):
64
64
53
8
55
oznurkalkar/polynom
polynom/ecc/__init__.py
Python
PairingFriendlyCurve
PairingFriendlyCurve
51
57
51
52
0f69d35f88ff73553200bf7bb7cd7b16620be669
bigcode/the-stack
train
7ee5e4fb41518c982857e470
train
class
class Migration(migrations.Migration): dependencies = [ ('notes', '0010_auto_20191126_1041'), ] operations = [ migrations.AlterField( model_name='note', name='media', field=models.ImageField(blank=True, help_text='Optional image to add to note.', upload_...
class Migration(migrations.Migration):
dependencies = [ ('notes', '0010_auto_20191126_1041'), ] operations = [ migrations.AlterField( model_name='note', name='media', field=models.ImageField(blank=True, help_text='Optional image to add to note.', upload_to=b'media'), ), ]
# Generated by Django 2.2.5 on 2019-11-26 19:11 from django.db import migrations, models class Migration(migrations.Migration):
38
64
77
7
30
UPstartDeveloper/explorer_buddy
explorer/notes/migrations/0011_auto_20191126_1111.py
Python
Migration
Migration
6
18
6
7
7f6b88c16be60338480d168711ae81f010f8bc8c
bigcode/the-stack
train
532877c5dd28e5e230ee58e9
train
class
class RemoteListener(pykka.ThreadingActor, CoreListener): def __init__(self, config, core): super(RemoteListener, self).__init__() self.core = core self.config = config self.player = Remote(core,config) self.library = RemoteLibrary(config) logger.info("Listener initi...
class RemoteListener(pykka.ThreadingActor, CoreListener):
def __init__(self, config, core): super(RemoteListener, self).__init__() self.core = core self.config = config self.player = Remote(core,config) self.library = RemoteLibrary(config) logger.info("Listener initialized") def on_stop(self): logger.info("Remot...
import logging import pykka from mopidy.core import CoreListener from .library import RemoteLibrary from .frontend import Remote logger = logging.getLogger(__name__) class RemoteListener(pykka.ThreadingActor, CoreListener):
49
155
517
12
37
rawdlite/mopidy-remote
mopidy_remote/listener.py
Python
RemoteListener
RemoteListener
10
58
10
11
356ca3a45c228b583f68463f7f927fd0ebad2a76
bigcode/the-stack
train
b6adba67e421efdab614893b
train
function
def main(): # sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib')) # sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'packages')) if len(sys.argv) > 1 and sys.argv[1] == 'merge': merger = Merger() merger.run() sys.exit() ...
def main(): # sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib')) # sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'packages'))
if len(sys.argv) > 1 and sys.argv[1] == 'merge': merger = Merger() merger.run() sys.exit() # merger.remove_macros() app = QApplication(sys.argv) # Not merge,, i.e., header select headerSelector = HeaderSelector() if not headerSelector.run(): # Either no file se...
self.merge_sheet.api.VBProject.VBComponents.Remove("xlmerge") def main(): # sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib')) # sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'packages'))
63
64
148
48
15
june3474/xlmerge
xlmerge/xlmerge.py
Python
main
main
414
430
414
417
d9b51ff0b326709bb5037d7f85866229273e1905
bigcode/the-stack
train
5f5a2ab8b32cfefdf2c517eb
train
class
class HeaderSelector(QDialog): def __init__(self, parent=None, rows=10, cols=10): """Class for Selecting the header(title) row. ``HeaderSelector`` opens Excel first; let the user select Excel files to merge; read and show a part of the file so that the user selects the header row. ...
class HeaderSelector(QDialog):
def __init__(self, parent=None, rows=10, cols=10): """Class for Selecting the header(title) row. ``HeaderSelector`` opens Excel first; let the user select Excel files to merge; read and show a part of the file so that the user selects the header row. Selected headers are put th...
# -*- coding: utf-8 -*- import sys import os import openpyxl as pyxl import xlwings as xw from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QApplication, QDialog, QTableWidgetItem, QFileDialog, QMessageBox import win32gui from win32con import SW_MAXIMIZE from adodbapi.adodbapi import pywintypes ...
130
256
2,405
6
123
june3474/xlmerge
xlmerge/xlmerge.py
Python
HeaderSelector
HeaderSelector
17
295
17
17
ce5fabd78bd74e946757b665630f550b23e12c52
bigcode/the-stack
train
c86b5b3af82db464cbed6098
train
class
class Merger: def __init__(self): """Class for merging sheets This class performs merging based on the sheet HeaderSelector creates. """ # merge gets run only through the button click on the 'Headers' sheet self.excel = xw.apps.active self.wb = self.exce...
class Merger:
def __init__(self): """Class for merging sheets This class performs merging based on the sheet HeaderSelector creates. """ # merge gets run only through the button click on the 'Headers' sheet self.excel = xw.apps.active self.wb = self.excel.books.active ...
_btnNext_clicked(self): """다음 button handler""" self.write_to_excel() self.current_sheet += 1 self.load_sheet() @pyqtSlot() def on_btnFinish_clicked(self): """종료 button handler""" self.write_to_excel() # if 'Header' sheet is empty i...
256
256
992
4
251
june3474/xlmerge
xlmerge/xlmerge.py
Python
Merger
Merger
298
411
298
298
e50cd716affe34f5477b8ff4e45df33fc1ed2324
bigcode/the-stack
train
7d28da458febd1beef5f685c
train
class
class RubyRonn(Package): """Ronn builds manuals. It converts simple, human readable textfiles to roff for terminal display, and also to HTML for the web.""" homepage = "https://rubygems.org/gems/ronn" url = "https://github.com/rtomayko/ronn/archive/0.7.3.tar.gz" version('0.7.3', sha256='808aa...
class RubyRonn(Package):
"""Ronn builds manuals. It converts simple, human readable textfiles to roff for terminal display, and also to HTML for the web.""" homepage = "https://rubygems.org/gems/ronn" url = "https://github.com/rtomayko/ronn/archive/0.7.3.tar.gz" version('0.7.3', sha256='808aa6668f636ce03abba99c53c200...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RubyRonn(Package):
61
66
221
7
54
xiki-tempula/spack
var/spack/repos/builtin/packages/ruby-ronn/package.py
Python
RubyRonn
RubyRonn
9
23
9
9
b5a8868d80a533a5c6757433147ca6984df76cb0
bigcode/the-stack
train
fa5601154e8afe8284a1c611
train
function
def using_table_options_handler(entity, *args, **kwargs): entity._descriptor.table_args.extend(list(args)) entity._descriptor.table_options.update(kwargs)
def using_table_options_handler(entity, *args, **kwargs):
entity._descriptor.table_args.extend(list(args)) entity._descriptor.table_options.update(kwargs)
arg in kwargs: if kwarg in valid_options: setattr(entity._descriptor, kwarg, kwargs[kwarg]) else: raise Exception("'%s' is not a valid option for Elixir entities." % kwarg) def using_table_options_handler(entity, *args, **kwargs):
64
64
32
13
51
daqing15/elixir
elixir/options.py
Python
using_table_options_handler
using_table_options_handler
262
264
262
262
f3ce6cea9d9cf539c8a8f53274aa9089e7bf3206
bigcode/the-stack
train
f5cb6af2f45fd56796060982
train
function
def using_options_handler(entity, *args, **kwargs): for kwarg in kwargs: if kwarg in valid_options: setattr(entity._descriptor, kwarg, kwargs[kwarg]) else: raise Exception("'%s' is not a valid option for Elixir entities." % kwarg)
def using_options_handler(entity, *args, **kwargs):
for kwarg in kwargs: if kwarg in valid_options: setattr(entity._descriptor, kwarg, kwargs[kwarg]) else: raise Exception("'%s' is not a valid option for Elixir entities." % kwarg)
of hasattr to not check its presence within the # parent, and thus update the parent dict instead of creating a local dict. if not entity.__dict__.get('options_defaults'): entity.options_defaults = {} entity.options_defaults.update(kwargs) def using_options_handler(entity, *args, **kwargs):
64
64
66
12
52
daqing15/elixir
elixir/options.py
Python
using_options_handler
using_options_handler
253
259
253
253
f9aa95d31cf35b367f28a1be91a0235664a7d2b5
bigcode/the-stack
train
e576e5f0a567a4ddb5d7cd30
train
function
def using_options_defaults_handler(entity, **kwargs): for kwarg in kwargs: if kwarg not in valid_options: raise Exception("'%s' is not a valid option for Elixir entities." % kwarg) # We use __dict__ instead of hasattr to not check its presence within the # pa...
def using_options_defaults_handler(entity, **kwargs):
for kwarg in kwargs: if kwarg not in valid_options: raise Exception("'%s' is not a valid option for Elixir entities." % kwarg) # We use __dict__ instead of hasattr to not check its presence within the # parent, and thus update the parent dict instead of creat...
version_id_col=False, allowcoloverride=False, order_by=None, resolve_root=None, mapper_options={}, table_options={} ) valid_options = list(options_defaults.keys()) + [ 'metadata', 'session', 'collection' ] def using_options_defaults_handler(entity, **kwargs):
64
64
108
10
54
daqing15/elixir
elixir/options.py
Python
using_options_defaults_handler
using_options_defaults_handler
240
250
240
240
d55ad37920dccf0db827b2c874c11a4dae6a751a
bigcode/the-stack
train
8d0e2453434e41b12cb9c4ae
train
function
def default_m2m_column_formatter(data): if data['selfref']: return ALTERNATE_M2MCOL_NAMEFORMAT % data else: return OLD_M2MCOL_NAMEFORMAT % data
def default_m2m_column_formatter(data):
if data['selfref']: return ALTERNATE_M2MCOL_NAMEFORMAT % data else: return OLD_M2MCOL_NAMEFORMAT % data
Mutator __doc_all__ = ['options_defaults'] OLD_M2MCOL_NAMEFORMAT = "%(tablename)s_%(key)s%(numifself)s" ALTERNATE_M2MCOL_NAMEFORMAT = "%(inversename)s_%(key)s" def default_m2m_column_formatter(data):
64
64
45
9
55
daqing15/elixir
elixir/options.py
Python
default_m2m_column_formatter
default_m2m_column_formatter
190
194
190
190
0d9541b17e049bd9af4fc4fd1755fa857d01f3fd
bigcode/the-stack
train
5881394bcef928c8c815c030
train
function
def using_mapper_options_handler(entity, *args, **kwargs): entity._descriptor.mapper_options.update(kwargs)
def using_mapper_options_handler(entity, *args, **kwargs):
entity._descriptor.mapper_options.update(kwargs)
("'%s' is not a valid option for Elixir entities." % kwarg) def using_table_options_handler(entity, *args, **kwargs): entity._descriptor.table_args.extend(list(args)) entity._descriptor.table_options.update(kwargs) def using_mapper_options_handler(entity, *args, **kwargs):
64
64
22
13
51
daqing15/elixir
elixir/options.py
Python
using_mapper_options_handler
using_mapper_options_handler
267
268
267
267
152bc2763e178aa53305b3f803ec62591f1251f4
bigcode/the-stack
train
a1698a8d29f3a60c946c99bd
train
function
def test_finds_all_attribute_methods(browser): assert hasattr(browser.delete(index=0), 'class_name') assert hasattr(browser.delete(index=0), 'id') assert hasattr(browser.delete(index=0), 'title') assert hasattr(browser.delete(index=0), 'text')
def test_finds_all_attribute_methods(browser):
assert hasattr(browser.delete(index=0), 'class_name') assert hasattr(browser.delete(index=0), 'id') assert hasattr(browser.delete(index=0), 'title') assert hasattr(browser.delete(index=0), 'text')
no_such_id']"}]) @pytest.mark.usefixtures('quick_timeout') def test_raises_correct_exception_for_text_if_element_does_not_exist(self, browser, selector): with pytest.raises(UnknownObjectException): browser.delete(**selector).text def test_finds_all_attribute_methods(browser):
64
64
58
9
54
harsh183/nerodia
tests/browser/elements/delete_tests.py
Python
test_finds_all_attribute_methods
test_finds_all_attribute_methods
89
93
89
89
20747515bda8e3cd9c5ec77f5c1b3d377ae514c9
bigcode/the-stack
train
94618e84fc4f501caddf1c3c
train
class
class TestDeleteExist(object): def test_returns_true_if_the_delete_exists(self, browser): assert browser.delete(id='lead').exists assert browser.delete(id=compile(r'lead')).exists assert browser.delete(text='This is a deleted text tag 1').exists assert browser.delete(text=compile(r'T...
class TestDeleteExist(object):
def test_returns_true_if_the_delete_exists(self, browser): assert browser.delete(id='lead').exists assert browser.delete(id=compile(r'lead')).exists assert browser.delete(text='This is a deleted text tag 1').exists assert browser.delete(text=compile(r'This is a deleted text tag 1'))....
from re import compile import pytest from nerodia.exception import UnknownObjectException pytestmark = pytest.mark.page('non_control_elements.html') class TestDeleteExist(object):
35
97
326
6
29
harsh183/nerodia
tests/browser/elements/delete_tests.py
Python
TestDeleteExist
TestDeleteExist
10
36
10
10
048a4967d3783a3bb8a392feb7bc22c481571fc6
bigcode/the-stack
train
b9d28a3873c7b168d00d7942
train
class
class TestDeleteAttributes(object): # id def test_returns_the_id_attribute_if_element_exists(self, browser): assert browser.delete(index=0).id == 'lead' def test_returns_an_empty_string_if_element_exists_but_id_doesnt(self, browser): assert browser.delete(index=2).id == '' @pytest.mar...
class TestDeleteAttributes(object): # id
def test_returns_the_id_attribute_if_element_exists(self, browser): assert browser.delete(index=0).id == 'lead' def test_returns_an_empty_string_if_element_exists_but_id_doesnt(self, browser): assert browser.delete(index=2).id == '' @pytest.mark.parametrize('selector', ...
uch_text').exists assert not browser.delete(text=compile(r'no_such_text')).exists assert not browser.delete(class_name='no_such_class').exists assert not browser.delete(class_name=compile(r'no_such_class')).exists assert not browser.delete(index=1337).exists assert not browser.de...
130
130
436
10
119
harsh183/nerodia
tests/browser/elements/delete_tests.py
Python
TestDeleteAttributes
TestDeleteAttributes
39
86
39
41
d7d31e27e230e3d3520f51773aaad7b9e6d3a228
bigcode/the-stack
train
5cc0086c998e1804052440ac
train
class
class TestDeleteManipulation(object): # click def test_fires_events(self, browser): delete = browser.delete(class_name='footer') assert 'Javascript' not in delete.text delete.click() assert 'Javascript' in delete.text @pytest.mark.parametrize('selector', ...
class TestDeleteManipulation(object): # click
def test_fires_events(self, browser): delete = browser.delete(class_name='footer') assert 'Javascript' not in delete.text delete.click() assert 'Javascript' in delete.text @pytest.mark.parametrize('selector', [{'id': 'no_such_id'}, ...
_attribute_methods(browser): assert hasattr(browser.delete(index=0), 'class_name') assert hasattr(browser.delete(index=0), 'id') assert hasattr(browser.delete(index=0), 'title') assert hasattr(browser.delete(index=0), 'text') class TestDeleteManipulation(object): # click
64
64
129
11
53
harsh183/nerodia
tests/browser/elements/delete_tests.py
Python
TestDeleteManipulation
TestDeleteManipulation
96
111
96
98
ed725cabbbdba4a6459801fa6665cca833fe6395
bigcode/the-stack
train
ee69e58becf236d2a7b32396
train
function
def train(env: Union[gym.Wrapper, Simulator], agent: Agent, config: TrainConfig) -> type(None): obs = env.reset() trainer = config.build_trainer(agent, env) trainer.register_obs(obs) for _ in range(config.steps): act = trainer.model_step(obs) obs, reward, done, info = env.step(act) ...
def train(env: Union[gym.Wrapper, Simulator], agent: Agent, config: TrainConfig) -> type(None):
obs = env.reset() trainer = config.build_trainer(agent, env) trainer.register_obs(obs) for _ in range(config.steps): act = trainer.model_step(obs) obs, reward, done, info = env.step(act) trainer.register_obs(obs, done, reward) if done: obs = env.reset() ...
typing import Union import gym from gym_duckietown.simulator import Simulator from golem_driving.agents.agent import Agent from golem_driving.config import TrainConfig def train(env: Union[gym.Wrapper, Simulator], agent: Agent, config: TrainConfig) -> type(None):
64
64
135
25
38
KNSI-Golem/Duckietown-Driving-Olympics
golem_driving/run/train.py
Python
train
train
11
28
11
11
ed2eb27fb89031051959eadeded22eb37600482f
bigcode/the-stack
train
6a6dcfe5038c7f75b133ab0d
train
function
def translate_y_abs(img, pixels, **kwargs): _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs)
def translate_y_abs(img, pixels, **kwargs):
_check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs)
**kwargs) def translate_x_abs(img, pixels, **kwargs): _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs) def translate_y_abs(img, pixels, **kwargs):
64
64
50
11
53
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
translate_y_abs
translate_y_abs
85
87
85
85
4d0bf8d4bece66968ac62dddbd1c61119e72a9b8
bigcode/the-stack
train
ef29b97c314758f53356f1ef
train
function
def equalize(img, **__): return ImageOps.equalize(img)
def equalize(img, **__):
return ImageOps.equalize(img)
matrix, **kwargs) else: return img.rotate(degrees, resample=kwargs['resample']) def auto_contrast(img, **__): return ImageOps.autocontrast(img) def invert(img, **__): return ImageOps.invert(img) def equalize(img, **__):
64
64
16
8
56
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
equalize
equalize
130
131
130
130
68def841db62d415816ce7ce76a25a95b1c8bf53
bigcode/the-stack
train
41b69cf296940ee586abee0a
train
function
def _enhance_level_to_arg(level, _hparams): # range [0.1, 1.9] return (level / _MAX_LEVEL) * 1.8 + 0.1,
def _enhance_level_to_arg(level, _hparams): # range [0.1, 1.9]
return (level / _MAX_LEVEL) * 1.8 + 0.1,
): # range [-30, 30] level = (level / _MAX_LEVEL) * 30. level = _randomly_negate(level) return level, def _enhance_level_to_arg(level, _hparams): # range [0.1, 1.9]
64
64
46
26
38
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_enhance_level_to_arg
_enhance_level_to_arg
187
189
187
188
e683059a27faa868b6c81507006364dad16ab63f
bigcode/the-stack
train
0c03ef1b6c3b2b6bd4734e12
train
function
def auto_augment_policy(name='v0', hparams=None): hparams = hparams or _HPARAMS_DEFAULT if name == 'original': return auto_augment_policy_original(hparams) elif name == 'originalr': return auto_augment_policy_originalr(hparams) elif name == 'v0': return auto_augment_policy_v0(hpa...
def auto_augment_policy(name='v0', hparams=None):
hparams = hparams or _HPARAMS_DEFAULT if name == 'original': return auto_augment_policy_original(hparams) elif name == 'originalr': return auto_augment_policy_originalr(hparams) elif name == 'v0': return auto_augment_policy_v0(hparams) elif name == 'v0r': return auto_...
0.8, 8), ('Equalize', 0.6, 3)], ] pc = [[AugmentOp(*a, hparams=hparams) for a in sp] for sp in policy] return pc def auto_augment_policy(name='v0', hparams=None):
64
64
120
14
49
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
auto_augment_policy
auto_augment_policy
481
492
481
481
21c4f422c63c1eae1720bdd5f40403ddfa9c294f
bigcode/the-stack
train
36852ad36f8b1cadcfbc239e
train
function
def shear_x(img, factor, **kwargs): _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, factor, 0, 0, 1, 0), **kwargs)
def shear_x(img, factor, **kwargs):
_check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, factor, 0, 0, 1, 0), **kwargs)
) else: return interpolation def _check_args_tf(kwargs): if 'fillcolor' in kwargs and _PIL_VER < (5, 0): kwargs.pop('fillcolor') kwargs['resample'] = _interpolation(kwargs) def shear_x(img, factor, **kwargs):
64
64
49
10
54
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
shear_x
shear_x
58
60
58
58
aa85595c6424a25c5ee70610b30ec88633220f99
bigcode/the-stack
train
475f6ad4c86cc85b1882e578
train
function
def posterize(img, bits_to_keep, **__): if bits_to_keep >= 8: return img return ImageOps.posterize(img, bits_to_keep)
def posterize(img, bits_to_keep, **__):
if bits_to_keep >= 8: return img return ImageOps.posterize(img, bits_to_keep)
) if img.mode in ("L", "RGB"): if img.mode == "RGB" and len(lut) == 256: lut = lut + lut + lut return img.point(lut) else: return img def posterize(img, bits_to_keep, **__):
64
64
37
12
51
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
posterize
posterize
153
156
153
153
387bdbe028879bb1c3e98f55733c6d44c31e8153
bigcode/the-stack
train
099539e23420317f55a31c94
train
function
def _translate_rel_level_to_arg(level, hparams): # default range [-0.45, 0.45] translate_pct = hparams.get('translate_pct', 0.45) level = (level / _MAX_LEVEL) * translate_pct level = _randomly_negate(level) return level,
def _translate_rel_level_to_arg(level, hparams): # default range [-0.45, 0.45]
translate_pct = hparams.get('translate_pct', 0.45) level = (level / _MAX_LEVEL) * translate_pct level = _randomly_negate(level) return level,
_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): # default range [-0.45, 0.45]
64
64
70
26
38
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_translate_rel_level_to_arg
_translate_rel_level_to_arg
214
219
214
215
54264e0204a070734c2309b793ba86b50fb0fc5c
bigcode/the-stack
train
09b42a5bb0f947a45be5781c
train
function
def _posterize_level_to_arg(level, _hparams): # As per Tensorflow TPU EfficientNet impl # range [0, 4], 'keep 0 up to 4 MSB of original image' # intensity/severity of augmentation decreases with level return int((level / _MAX_LEVEL) * 4),
def _posterize_level_to_arg(level, _hparams): # As per Tensorflow TPU EfficientNet impl # range [0, 4], 'keep 0 up to 4 MSB of original image' # intensity/severity of augmentation decreases with level
return int((level / _MAX_LEVEL) * 4),
(level) return level, def _posterize_level_to_arg(level, _hparams): # As per Tensorflow TPU EfficientNet impl # range [0, 4], 'keep 0 up to 4 MSB of original image' # intensity/severity of augmentation decreases with level
64
64
72
58
6
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_posterize_level_to_arg
_posterize_level_to_arg
222
226
222
225
19530de306ddc463a2f003935f007ab9fbf98794
bigcode/the-stack
train
5dd8fc699993e05079e46fef
train
function
def contrast(img, factor, **__): return ImageEnhance.Contrast(img).enhance(factor)
def contrast(img, factor, **__):
return ImageEnhance.Contrast(img).enhance(factor)
lut + lut return img.point(lut) else: return img def posterize(img, bits_to_keep, **__): if bits_to_keep >= 8: return img return ImageOps.posterize(img, bits_to_keep) def contrast(img, factor, **__):
64
64
23
9
55
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
contrast
contrast
159
160
159
159
56175c8fecbda78f8d5924a95f45144fb8f745dd
bigcode/the-stack
train
d4faae133cf55b17d2d95ce5
train
function
def translate_y_rel(img, pct, **kwargs): pixels = pct * img.size[1] _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs)
def translate_y_rel(img, pct, **kwargs):
pixels = pct * img.size[1] _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs)
, **kwargs): pixels = pct * img.size[0] _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs) def translate_y_rel(img, pct, **kwargs):
64
64
60
11
53
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
translate_y_rel
translate_y_rel
74
77
74
74
cebf7f934c3adf0dc54fd66ec711d89f46d86956
bigcode/the-stack
train
91c26bf2058913ded8470fe3
train
function
def _randomly_negate(v): """With 50% prob, negate the value""" return -v if random.random() > 0.5 else v
def _randomly_negate(v):
"""With 50% prob, negate the value""" return -v if random.random() > 0.5 else v
(img).enhance(factor) def brightness(img, factor, **__): return ImageEnhance.Brightness(img).enhance(factor) def sharpness(img, factor, **__): return ImageEnhance.Sharpness(img).enhance(factor) def _randomly_negate(v):
64
64
36
8
56
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_randomly_negate
_randomly_negate
175
177
175
175
55a62b654c94c4711b0eff47a83a97943478df1a
bigcode/the-stack
train
817c1ac290087b06c56cb84d
train
function
def rand_augment_transform(config_str, hparams): """ Create a RandAugment transform :param config_str: String defining configuration of random augmentation. Consists of multiple sections separated by dashes ('-'). The first section defines the specific variant of rand augment (currently only 'rand'). T...
def rand_augment_transform(config_str, hparams):
""" Create a RandAugment transform :param config_str: String defining configuration of random augmentation. Consists of multiple sections separated by dashes ('-'). The first section defines the specific variant of rand augment (currently only 'rand'). The remaining sections, not order sepecific de...
params = 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_l...
169
169
564
11
157
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
rand_augment_transform
rand_augment_transform
631
678
631
631
a86559c525c11ba6b37b0bbdb414e08cbe343fd2
bigcode/the-stack
train
f411b2ab9ea7cd7c0d05758e
train
function
def auto_augment_policy_originalr(hparams): # ImageNet policy from https://arxiv.org/abs/1805.09501 with research posterize variation policy = [ [('PosterizeIncreasing', 0.4, 8), ('Rotate', 0.6, 9)], [('Solarize', 0.6, 5), ('AutoContrast', 0.6, 5)], [('Equalize', 0.8, 8), ('Equalize', 0....
def auto_augment_policy_originalr(hparams): # ImageNet policy from https://arxiv.org/abs/1805.09501 with research posterize variation
policy = [ [('PosterizeIncreasing', 0.4, 8), ('Rotate', 0.6, 9)], [('Solarize', 0.6, 5), ('AutoContrast', 0.6, 5)], [('Equalize', 0.8, 8), ('Equalize', 0.6, 3)], [('PosterizeIncreasing', 0.6, 7), ('PosterizeIncreasing', 0.6, 6)], [('Equalize', 0.4, 7), ('Solarize', 0.2, 4)], ...
4, 0), ('Equalize', 0.6, 3)], [('Equalize', 0.4, 7), ('Solarize', 0.2, 4)], [('Solarize', 0.6, 5), ('AutoContrast', 0.6, 5)], [('Invert', 0.6, 4), ('Equalize', 1.0, 8)], [('Color', 0.6, 4), ('Contrast', 1.0, 8)], [('Equalize', 0.8, 8), ('Equalize', 0.6, 3)], ] pc = [[Augm...
205
205
684
35
169
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
auto_augment_policy_originalr
auto_augment_policy_originalr
448
478
448
449
9f0aa5772e63b8797f574d93a19eaa6d903da669
bigcode/the-stack
train
ad22a3732880513945c424c2
train
function
def _solarize_add_level_to_arg(level, _hparams): # range [0, 110] return int((level / _MAX_LEVEL) * 110),
def _solarize_add_level_to_arg(level, _hparams): # range [0, 110]
return int((level / _MAX_LEVEL) * 110),
): # range [0, 256] # intensity/severity of augmentation increases with level return 256 - _solarize_level_to_arg(level, _hparams)[0], def _solarize_add_level_to_arg(level, _hparams): # range [0, 110]
63
64
37
23
40
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_solarize_add_level_to_arg
_solarize_add_level_to_arg
255
257
255
256
0c39dcaf671a5de211b305ca3e3ee3d72cb2590e
bigcode/the-stack
train
932ca65754e8b9f795242d2f
train
function
def _interpolation(kwargs): interpolation = kwargs.pop('resample', Image.BILINEAR) if isinstance(interpolation, (list, tuple)): return random.choice(interpolation) else: return interpolation
def _interpolation(kwargs):
interpolation = kwargs.pop('resample', Image.BILINEAR) if isinstance(interpolation, (list, tuple)): return random.choice(interpolation) else: return interpolation
the controller RNN could predict for the # augmentation scheme. _MAX_LEVEL = 10. _HPARAMS_DEFAULT = dict( translate_const=250, img_mean=_FILL, ) _RANDOM_INTERPOLATION = (Image.BILINEAR, Image.BICUBIC) def _interpolation(kwargs):
64
64
46
6
58
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_interpolation
_interpolation
44
49
44
44
a2a5a1e3fed0ee68a869153d3fbd32f3fb75c02e
bigcode/the-stack
train
3761275482f708954c964c04
train
function
def brightness(img, factor, **__): return ImageEnhance.Brightness(img).enhance(factor)
def brightness(img, factor, **__):
return ImageEnhance.Brightness(img).enhance(factor)
ImageOps.posterize(img, bits_to_keep) def contrast(img, factor, **__): return ImageEnhance.Contrast(img).enhance(factor) def color(img, factor, **__): return ImageEnhance.Color(img).enhance(factor) def brightness(img, factor, **__):
64
64
23
9
55
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
brightness
brightness
167
168
167
167
0df60cae719952f47be2e3c50c36e34d5d54c36e
bigcode/the-stack
train
1a211901e5b361231f8322c3
train
function
def augmix_ops(magnitude=10, hparams=None, transforms=None): hparams = hparams or _HPARAMS_DEFAULT transforms = transforms or _AUGMIX_TRANSFORMS return [AugmentOp( name, prob=1.0, magnitude=magnitude, hparams=hparams) for name in transforms]
def augmix_ops(magnitude=10, hparams=None, transforms=None):
hparams = hparams or _HPARAMS_DEFAULT transforms = transforms or _AUGMIX_TRANSFORMS return [AugmentOp( name, prob=1.0, magnitude=magnitude, hparams=hparams) for name in transforms]
paper 'Equalize', 'Rotate', 'PosterizeIncreasing', 'SolarizeIncreasing', 'ShearX', 'ShearY', 'TranslateXRel', 'TranslateYRel', ] def augmix_ops(magnitude=10, hparams=None, transforms=None):
64
64
73
16
48
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
augmix_ops
augmix_ops
698
702
698
698
8b74e92b60b24215a520e015ba3119776355ce5e
bigcode/the-stack
train
994bcf21d8601db879a4c8a1
train
function
def auto_augment_policy_original(hparams): # ImageNet policy from https://arxiv.org/abs/1805.09501 policy = [ [('PosterizeOriginal', 0.4, 8), ('Rotate', 0.6, 9)], [('Solarize', 0.6, 5), ('AutoContrast', 0.6, 5)], [('Equalize', 0.8, 8), ('Equalize', 0.6, 3)], [('PosterizeOriginal'...
def auto_augment_policy_original(hparams): # ImageNet policy from https://arxiv.org/abs/1805.09501
policy = [ [('PosterizeOriginal', 0.4, 8), ('Rotate', 0.6, 9)], [('Solarize', 0.6, 5), ('AutoContrast', 0.6, 5)], [('Equalize', 0.8, 8), ('Equalize', 0.6, 3)], [('PosterizeOriginal', 0.6, 7), ('PosterizeOriginal', 0.6, 6)], [('Equalize', 0.4, 7), ('Solarize', 0.2, 4)], ...
8, 4), ('Equalize', 0.0, 8)], [('Equalize', 1.0, 4), ('AutoContrast', 0.6, 2)], [('ShearY', 0.4, 7), ('SolarizeAdd', 0.6, 7)], [('PosterizeIncreasing', 0.8, 2), ('Solarize', 0.6, 10)], [('Solarize', 0.6, 8), ('Equalize', 0.6, 1)], [('Color', 0.8, 6), ('Rotate', 0.4, 5)], ] ...
203
203
678
29
173
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
auto_augment_policy_original
auto_augment_policy_original
415
445
415
416
6156e7ce452e8f0f241a2e2a811cf849a545d1ce
bigcode/the-stack
train
de6ac819a3f307f03feb02e1
train
class
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): # no replacement when using weighted choice ops = np.random.choice( self.o...
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): # no replacement when using weighted choice ops = np.random.choice( self.ops, self.num_layers...
=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:
64
64
106
5
59
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
RandAugment
RandAugment
616
628
616
616
7c9439e718e9fa322ba8bfac6e89a68c51785451
bigcode/the-stack
train
2d10f4691c0d6fb7ee35926c
train
function
def sharpness(img, factor, **__): return ImageEnhance.Sharpness(img).enhance(factor)
def sharpness(img, factor, **__):
return ImageEnhance.Sharpness(img).enhance(factor)
.Contrast(img).enhance(factor) def color(img, factor, **__): return ImageEnhance.Color(img).enhance(factor) def brightness(img, factor, **__): return ImageEnhance.Brightness(img).enhance(factor) def sharpness(img, factor, **__):
64
64
26
10
54
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
sharpness
sharpness
171
172
171
171
b1b4dcc787bfe7488a5d1d1a54193b1c859e5745
bigcode/the-stack
train
fa2e7e8629bde843c1de0e8f
train
function
def auto_augment_transform(config_str, hparams): """ Create a AutoAugment transform :param config_str: String defining configuration of auto augmentation. Consists of multiple sections separated by dashes ('-'). The first section defines the AutoAugment policy (one of 'v0', 'v0r', 'original', 'original...
def auto_augment_transform(config_str, hparams):
""" Create a AutoAugment transform :param config_str: String defining configuration of auto augmentation. Consists of multiple sections separated by dashes ('-'). The first section defines the AutoAugment policy (one of 'v0', 'v0r', 'original', 'originalr'). The remaining sections, not order sepeci...
r(hparams) else: assert False, 'Unknown AA policy (%s)' % name class AutoAugment: def __init__(self, policy): self.policy = policy def __call__(self, img): sub_policy = random.choice(self.policy) for op in sub_policy: img = op(img) return img def auto_...
87
87
293
11
75
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
auto_augment_transform
auto_augment_transform
507
535
507
507
70bf43631d64cd803dc49f8a1834aab1c63d238e
bigcode/the-stack
train
d66bf7451ae4d307b09a45fb
train
function
def _select_rand_weights(weight_idx=0, transforms=None): transforms = transforms or _RAND_TRANSFORMS assert weight_idx == 0 # only one set of weights currently rand_weights = _RAND_CHOICE_WEIGHTS_0 probs = [rand_weights[k] for k in transforms] probs /= np.sum(probs) return probs
def _select_rand_weights(weight_idx=0, transforms=None):
transforms = transforms or _RAND_TRANSFORMS assert weight_idx == 0 # only one set of weights currently rand_weights = _RAND_CHOICE_WEIGHTS_0 probs = [rand_weights[k] for k in transforms] probs /= np.sum(probs) return probs
': .005, 'SolarizeAdd': .005, 'Contrast': .005, 'Brightness': .005, 'Equalize': .005, 'Posterize': 0, 'Invert': 0, } def _select_rand_weights(weight_idx=0, transforms=None):
64
64
78
13
51
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_select_rand_weights
_select_rand_weights
600
606
600
600
968c05853f87cf881fc46604763d1b306c4072b0
bigcode/the-stack
train
0e849fe9ffd5fb86ee0513aa
train
function
def solarize_add(img, add, thresh=128, **__): lut = [] for i in range(256): if i < thresh: lut.append(min(255, i + add)) else: lut.append(i) if img.mode in ("L", "RGB"): if img.mode == "RGB" and len(lut) == 256: lut = lut + lut + lut return...
def solarize_add(img, add, thresh=128, **__):
lut = [] for i in range(256): if i < thresh: lut.append(min(255, i + add)) else: lut.append(i) if img.mode in ("L", "RGB"): if img.mode == "RGB" and len(lut) == 256: lut = lut + lut + lut return img.point(lut) else: return img
, **__): return ImageOps.invert(img) def equalize(img, **__): return ImageOps.equalize(img) def solarize(img, thresh, **__): return ImageOps.solarize(img, thresh) def solarize_add(img, add, thresh=128, **__):
64
64
103
15
49
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
solarize_add
solarize_add
138
150
138
138
ea0325840a8439fad5211ee67d2d2ab2927cc004
bigcode/the-stack
train
1fa791004a3b5c450f0608d4
train
function
def rotate(img, degrees, **kwargs): _check_args_tf(kwargs) if _PIL_VER >= (5, 2): return img.rotate(degrees, **kwargs) elif _PIL_VER >= (5, 0): w, h = img.size post_trans = (0, 0) rotn_center = (w / 2.0, h / 2.0) angle = -math.radians(degrees) matrix = [ ...
def rotate(img, degrees, **kwargs):
_check_args_tf(kwargs) if _PIL_VER >= (5, 2): return img.rotate(degrees, **kwargs) elif _PIL_VER >= (5, 0): w, h = img.size post_trans = (0, 0) rotn_center = (w / 2.0, h / 2.0) angle = -math.radians(degrees) matrix = [ round(math.cos(angle), 15), ...
return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs) def translate_y_abs(img, pixels, **kwargs): _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs) def rotate(img, degrees, **kwargs):
91
91
305
9
82
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
rotate
rotate
90
119
90
90
2f14e6fdc542be64c70009d84dce962784b06545
bigcode/the-stack
train
39c56e12317e3b4b26af2936
train
class
class AugMixAugment: """ AugMix Transform Adapted and improved from impl here: https://github.com/google-research/augmix/blob/master/imagenet.py From paper: 'AugMix: A Simple Data Processing Method to Improve Robustness and Uncertainty - https://arxiv.org/abs/1912.02781 """ def __init__(self, op...
class AugMixAugment:
""" AugMix Transform Adapted and improved from impl here: https://github.com/google-research/augmix/blob/master/imagenet.py From paper: 'AugMix: A Simple Data Processing Method to Improve Robustness and Uncertainty - https://arxiv.org/abs/1912.02781 """ def __init__(self, ops, alpha=1., width=3,...
choice_weights = None if weight_idx is None else _select_rand_weights(weight_idx) return RandAugment(ra_ops, num_layers, choice_weights=choice_weights) _AUGMIX_TRANSFORMS = [ 'AutoContrast', 'ColorIncreasing', # not in paper 'ContrastIncreasing', # not in paper 'BrightnessIncreasing', # not...
220
220
734
6
214
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
AugMixAugment
AugMixAugment
705
768
705
705
7813eb64c05aafa49dc0a2fbb7e8ac34fe8b7f2d
bigcode/the-stack
train
89d6b8e1b553ea4e1c486197
train
function
def shear_y(img, factor, **kwargs): _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, 0, factor, 1, 0), **kwargs)
def shear_y(img, factor, **kwargs):
_check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, 0, factor, 1, 0), **kwargs)
_interpolation(kwargs) def shear_x(img, factor, **kwargs): _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, factor, 0, 0, 1, 0), **kwargs) def shear_y(img, factor, **kwargs):
64
64
49
10
54
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
shear_y
shear_y
63
65
63
63
eef27773c2cc43e4e3e0d47d67e96875e5d22578
bigcode/the-stack
train
a80a9a10e3b5a00b5d006f5a
train
function
def translate_x_abs(img, pixels, **kwargs): _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs)
def translate_x_abs(img, pixels, **kwargs):
_check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs)
, **kwargs): pixels = pct * img.size[1] _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs) def translate_x_abs(img, pixels, **kwargs):
64
64
50
11
53
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
translate_x_abs
translate_x_abs
80
82
80
80
4ae9044193819cbb0c30064bfa98f28f3dadef23
bigcode/the-stack
train
0f6b7cfc2171df2f6edf194c
train
function
def solarize(img, thresh, **__): return ImageOps.solarize(img, thresh)
def solarize(img, thresh, **__):
return ImageOps.solarize(img, thresh)
kwargs['resample']) def auto_contrast(img, **__): return ImageOps.autocontrast(img) def invert(img, **__): return ImageOps.invert(img) def equalize(img, **__): return ImageOps.equalize(img) def solarize(img, thresh, **__):
64
64
21
10
54
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
solarize
solarize
134
135
134
134
dee347b2baa0fc09c2cb6dd4998884f72551e851
bigcode/the-stack
train
75771b9469d4e77bff250e99
train
function
def _rotate_level_to_arg(level, _hparams): # range [-30, 30] level = (level / _MAX_LEVEL) * 30. level = _randomly_negate(level) return level,
def _rotate_level_to_arg(level, _hparams): # range [-30, 30]
level = (level / _MAX_LEVEL) * 30. level = _randomly_negate(level) return level,
(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): # range [-30, 30]
64
64
49
21
42
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_rotate_level_to_arg
_rotate_level_to_arg
180
184
180
181
80a8a17ef95f30ea18d8fe4da2f00f8d6be6b56d
bigcode/the-stack
train
5468cb018ace5e13f5284ce9
train
function
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]
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]
# only one set of weights currently 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):
64
64
71
17
46
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
rand_augment_ops
rand_augment_ops
609
613
609
609
11235dd2e89f862f70078db5e094d4f5175c782d
bigcode/the-stack
train
623627e9d83195a796506c83
train
function
def auto_contrast(img, **__): return ImageOps.autocontrast(img)
def auto_contrast(img, **__):
return ImageOps.autocontrast(img)
+= rotn_center[0] matrix[5] += rotn_center[1] return img.transform(img.size, Image.AFFINE, matrix, **kwargs) else: return img.rotate(degrees, resample=kwargs['resample']) def auto_contrast(img, **__):
63
64
17
9
54
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
auto_contrast
auto_contrast
122
123
122
122
5b4a12ce6170a1e726dfb6891ee8e1001630b770
bigcode/the-stack
train
d09b71c9ce944ad4fec2f91d
train
function
def invert(img, **__): return ImageOps.invert(img)
def invert(img, **__):
return ImageOps.invert(img)
_center[1] return img.transform(img.size, Image.AFFINE, matrix, **kwargs) else: return img.rotate(degrees, resample=kwargs['resample']) def auto_contrast(img, **__): return ImageOps.autocontrast(img) def invert(img, **__):
64
64
15
7
57
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
invert
invert
126
127
126
126
892659fd45d58f0f4afd17143c36d08062709696
bigcode/the-stack
train
f0b1d92a00d7513a0274045e
train
function
def augment_and_mix_transform(config_str, hparams): """ Create AugMix PyTorch transform :param config_str: String defining configuration of random augmentation. Consists of multiple sections separated by dashes ('-'). The first section defines the specific variant of rand augment (currently only 'rand'). T...
def augment_and_mix_transform(config_str, hparams):
""" Create AugMix PyTorch transform :param config_str: String defining configuration of random augmentation. Consists of multiple sections separated by dashes ('-'). The first section defines the specific variant of rand augment (currently only 'rand'). The remaining sections, not order sepecific deter...
np.asarray(img_aug, dtype=np.float32) np.clip(mixed, 0, 255., out=mixed) mixed = Image.fromarray(mixed.astype(np.uint8)) return Image.blend(img, mixed, m) def __call__(self, img): mixing_weights = np.float32(np.random.dirichlet([self.alpha] * self.width)) m = np.float32(np....
147
147
493
11
135
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
augment_and_mix_transform
augment_and_mix_transform
771
817
771
771
f5a739a2dfc81b4a9f29a2491a3267348d106904
bigcode/the-stack
train
9cfc1367ae29d43b326f0559
train
function
def _solarize_level_to_arg(level, _hparams): # range [0, 256] # intensity/severity of augmentation decreases with level return int((level / _MAX_LEVEL) * 256),
def _solarize_level_to_arg(level, _hparams): # range [0, 256] # intensity/severity of augmentation decreases with level
return int((level / _MAX_LEVEL) * 256),
image' # intensity/severity of augmentation decreases with level return int((level / _MAX_LEVEL) * 4) + 4, def _solarize_level_to_arg(level, _hparams): # range [0, 256] # intensity/severity of augmentation decreases with level
64
64
47
33
31
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_solarize_level_to_arg
_solarize_level_to_arg
243
246
243
245
7ed4cc55e6068bf925a116605753512c0e058dc5
bigcode/the-stack
train
9cee65ab7c150f8c5e2f5ddf
train
class
class AugmentOp: def __init__(self, name, prob=0.5, magnitude=10, hparams=None): hparams = hparams or _HPARAMS_DEFAULT self.aug_fn = NAME_TO_OP[name] # ! take an operation @NAME_TO_OP apply to @img self.level_fn = LEVEL_TO_ARG[name] self.prob = prob self.magnitude = magnitu...
class AugmentOp:
def __init__(self, name, prob=0.5, magnitude=10, hparams=None): hparams = hparams or _HPARAMS_DEFAULT self.aug_fn = NAME_TO_OP[name] # ! take an operation @NAME_TO_OP apply to @img self.level_fn = LEVEL_TO_ARG[name] self.prob = prob self.magnitude = magnitude self.hp...
'ColorIncreasing': color, 'Contrast': contrast, 'ContrastIncreasing': contrast, 'Brightness': brightness, 'BrightnessIncreasing': brightness, 'Sharpness': sharpness, 'SharpnessIncreasing': sharpness, 'ShearX': shear_x, 'ShearY': shear_y, 'TranslateX': translate_x_abs, 'Translate...
111
111
371
5
106
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
AugmentOp
AugmentOp
317
345
317
318
50866f306bae477805ed8a282395ca6dbe83e377
bigcode/the-stack
train
b5a14cb0214807ad88a73a6f
train
function
def color(img, factor, **__): return ImageEnhance.Color(img).enhance(factor)
def color(img, factor, **__):
return ImageEnhance.Color(img).enhance(factor)
bits_to_keep, **__): if bits_to_keep >= 8: return img return ImageOps.posterize(img, bits_to_keep) def contrast(img, factor, **__): return ImageEnhance.Contrast(img).enhance(factor) def color(img, factor, **__):
64
64
22
9
55
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
color
color
163
164
163
163
76691d01b7fe846444497c5495b406b520fb343a
bigcode/the-stack
train
1d9c6fda25a7bfcce7864eef
train
function
def _shear_level_to_arg(level, _hparams): # range [-0.3, 0.3] level = (level / _MAX_LEVEL) * 0.3 level = _randomly_negate(level) return level,
def _shear_level_to_arg(level, _hparams): # range [-0.3, 0.3]
level = (level / _MAX_LEVEL) * 0.3 level = _randomly_negate(level) return level,
1.9] level = (level / _MAX_LEVEL) * .9 level = 1.0 + _randomly_negate(level) return level, def _shear_level_to_arg(level, _hparams): # range [-0.3, 0.3]
64
64
56
26
38
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_shear_level_to_arg
_shear_level_to_arg
200
204
200
201
4d707187b322116fa40397326adaadfca3d3d15b
bigcode/the-stack
train
eff38fccc94638bf0eb7ba1f
train
function
def _posterize_original_level_to_arg(level, _hparams): # As per original AutoAugment paper description # range [4, 8], 'keep 4 up to 8 MSB of image' # intensity/severity of augmentation decreases with level return int((level / _MAX_LEVEL) * 4) + 4,
def _posterize_original_level_to_arg(level, _hparams): # As per original AutoAugment paper description # range [4, 8], 'keep 4 up to 8 MSB of image' # intensity/severity of augmentation decreases with level
return int((level / _MAX_LEVEL) * 4) + 4,
hparams)[0], def _posterize_original_level_to_arg(level, _hparams): # As per original AutoAugment paper description # range [4, 8], 'keep 4 up to 8 MSB of image' # intensity/severity of augmentation decreases with level
63
64
76
58
5
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_posterize_original_level_to_arg
_posterize_original_level_to_arg
236
240
236
239
b5d9de3c09bf2e35755cf9be63259cc46852ec8b
bigcode/the-stack
train
ae6afb5841f0e7669098b232
train
function
def auto_augment_policy_v0r(hparams): # ImageNet v0 policy from TPU EfficientNet impl, with variation of Posterize used # in Google research implementation (number of bits discarded increases with magnitude) policy = [ [('Equalize', 0.8, 1), ('ShearY', 0.8, 4)], [('Color', 0.4, 9), ('Equaliz...
def auto_augment_policy_v0r(hparams): # ImageNet v0 policy from TPU EfficientNet impl, with variation of Posterize used # in Google research implementation (number of bits discarded increases with magnitude)
policy = [ [('Equalize', 0.8, 1), ('ShearY', 0.8, 4)], [('Color', 0.4, 9), ('Equalize', 0.6, 3)], [('Color', 0.4, 1), ('Rotate', 0.6, 8)], [('Solarize', 0.8, 3), ('Equalize', 0.4, 7)], [('Solarize', 0.4, 2), ('Solarize', 0.6, 2)], [('Color', 0.2, 0), ('Equalize', 0.8,...
1.0, 4), ('AutoContrast', 0.6, 2)], [('ShearY', 0.4, 7), ('SolarizeAdd', 0.6, 7)], [('Posterize', 0.8, 2), ('Solarize', 0.6, 10)], # This results in black image with Tpu posterize [('Solarize', 0.6, 8), ('Equalize', 0.6, 1)], [('Color', 0.8, 6), ('Rotate', 0.4, 5)], ] pc = [[Au...
210
210
700
46
163
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
auto_augment_policy_v0r
auto_augment_policy_v0r
381
412
381
383
21fb0a4d5c19c76eeeb40e30509e606c9188e9bc
bigcode/the-stack
train
e555bbdae18be08e4b532d6e
train
function
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_abs_level_to_arg(level, hparams):
translate_const = hparams['translate_const'] level = (level / _MAX_LEVEL) * float(translate_const) level = _randomly_negate(level) return level,
_level_to_arg(level, _hparams): # range [-0.3, 0.3] level = (level / _MAX_LEVEL) * 0.3 level = _randomly_negate(level) return level, def _translate_abs_level_to_arg(level, hparams):
64
64
52
12
52
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_translate_abs_level_to_arg
_translate_abs_level_to_arg
207
211
207
207
58aeb3a14a1060a7b2fd94b02f9611c130e49dc0
bigcode/the-stack
train
7ad15220e60a4c53785ddfec
train
function
def auto_augment_policy_v0(hparams): # ImageNet v0 policy from TPU EfficientNet impl, cannot find a paper reference. policy = [ [('Equalize', 0.8, 1), ('ShearY', 0.8, 4)], [('Color', 0.4, 9), ('Equalize', 0.6, 3)], [('Color', 0.4, 1), ('Rotate', 0.6, 8)], [('Solarize', 0.8, 3), (...
def auto_augment_policy_v0(hparams): # ImageNet v0 policy from TPU EfficientNet impl, cannot find a paper reference.
policy = [ [('Equalize', 0.8, 1), ('ShearY', 0.8, 4)], [('Color', 0.4, 9), ('Equalize', 0.6, 3)], [('Color', 0.4, 1), ('Rotate', 0.6, 8)], [('Solarize', 0.8, 3), ('Equalize', 0.4, 7)], [('Solarize', 0.4, 2), ('Solarize', 0.6, 2)], [('Color', 0.2, 0), ('Equalize', 0.8,...
agnitude` and std-dev of `magnitude_std`. # NOTE This is my own hack, being tested, not in papers or reference impls. self.magnitude_std = self.hparams.get('magnitude_std', 0) def __call__(self, img): if self.prob < 1.0 and random.random() > self.prob: return img magnitu...
208
208
694
29
179
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
auto_augment_policy_v0
auto_augment_policy_v0
348
378
348
349
7f4baea6fc98911ed496e296367340de98be1e09
bigcode/the-stack
train
8a29efd64428060c1c0ce2a1
train
function
def _check_args_tf(kwargs): if 'fillcolor' in kwargs and _PIL_VER < (5, 0): kwargs.pop('fillcolor') kwargs['resample'] = _interpolation(kwargs)
def _check_args_tf(kwargs):
if 'fillcolor' in kwargs and _PIL_VER < (5, 0): kwargs.pop('fillcolor') kwargs['resample'] = _interpolation(kwargs)
.BILINEAR, Image.BICUBIC) def _interpolation(kwargs): interpolation = kwargs.pop('resample', Image.BILINEAR) if isinstance(interpolation, (list, tuple)): return random.choice(interpolation) else: return interpolation def _check_args_tf(kwargs):
64
64
46
7
56
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_check_args_tf
_check_args_tf
52
55
52
52
461be0f5da13b70ad5897535b1bb2227ca90ca61
bigcode/the-stack
train
80ce204851a00bf33c25b406
train
function
def _solarize_increasing_level_to_arg(level, _hparams): # range [0, 256] # intensity/severity of augmentation increases with level return 256 - _solarize_level_to_arg(level, _hparams)[0],
def _solarize_increasing_level_to_arg(level, _hparams): # range [0, 256] # intensity/severity of augmentation increases with level
return 256 - _solarize_level_to_arg(level, _hparams)[0],
256] # intensity/severity of augmentation decreases with level return int((level / _MAX_LEVEL) * 256), def _solarize_increasing_level_to_arg(level, _hparams): # range [0, 256] # intensity/severity of augmentation increases with level
63
64
54
35
28
datduong/pytorch-image-models
timm/data/auto_augment.py
Python
_solarize_increasing_level_to_arg
_solarize_increasing_level_to_arg
249
252
249
251
56094ec8128d5936b1aeaad4972202357ac2b252
bigcode/the-stack
train