Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def file_generator(self,
filepaths,
max_chars_per_file=None,
max_chars_total=None):
chars_total = 0
for fname in filepaths:
chars_this_file = 0
tf.logging.info("reading file %s" % fname)
... | [
"Read complete text of input files and yield unicode strings.\n\n By default, one unicode string is produced per file, but this is\n not guaranteed, since subclasses can override\n filepath_to_unicode_strings().\n\n max_chars_per_file and max_chars_total can also be specified, in which\n case some st... |
Please provide a description of the function:def example_generator(self, encoder, tmp_dir, task_id):
filepaths = self.text_filepaths_for_task(tmp_dir, task_id)
if task_id >= self.num_train_shards:
# this is dev data - limit the total length.
max_chars_per_file = self.max_dev_chars // (
... | [
"Generator for examples.\n\n Args:\n encoder: a TextEncoder\n tmp_dir: a string\n task_id: an integer\n Yields:\n feature dictionaries\n "
] |
Please provide a description of the function:def prepare_to_generate(self, data_dir, tmp_dir):
self.get_or_create_vocab(data_dir, tmp_dir)
self.train_text_filepaths(tmp_dir)
self.dev_text_filepaths(tmp_dir) | [
"Make sure that the data is prepared and the vocab is generated."
] |
Please provide a description of the function:def generate_data(self, data_dir, tmp_dir, task_id=-1):
tf.logging.info("generate_data task_id=%s" % task_id)
encoder = self.get_or_create_vocab(data_dir, tmp_dir)
assert task_id >= 0 and task_id < self.num_generate_tasks
if task_id < self.num_train_shar... | [
"Generates training/dev data.\n\n Args:\n data_dir: a string\n tmp_dir: a string\n task_id: an optional integer\n Returns:\n shard or shards for which data was generated.\n "
] |
Please provide a description of the function:def ConvBlock(kernel_size, filters, strides):
ks = kernel_size
filters1, filters2, filters3 = filters
main = layers.Serial(
layers.Conv(filters1, (1, 1), strides),
layers.BatchNorm(),
layers.Relu(),
layers.Conv(filters2, (ks, ks), padding='SA... | [
"ResNet convolutional striding block."
] |
Please provide a description of the function:def IdentityBlock(kernel_size, filters):
ks = kernel_size
filters1, filters2, filters3 = filters
main = layers.Serial(
layers.Conv(filters1, (1, 1)),
layers.BatchNorm(),
layers.Relu(),
layers.Conv(filters2, (ks, ks), padding='SAME'),
la... | [
"ResNet identical size block."
] |
Please provide a description of the function:def Resnet50(hidden_size=64, num_output_classes=1001, mode='train'):
del mode
return layers.Serial(
layers.Conv(hidden_size, (7, 7), (2, 2), 'SAME'),
layers.BatchNorm(), layers.Relu(),
layers.MaxPool(pool_size=(3, 3), strides=(2, 2)),
ConvBlock... | [
"ResNet.\n\n Args:\n hidden_size: the size of the first hidden layer (multiplied later).\n num_output_classes: how many classes to distinguish.\n mode: whether we are training or evaluating or doing inference.\n\n Returns:\n The ResNet model with the given layer and output sizes.\n "
] |
Please provide a description of the function:def WideResnetBlock(channels, strides=(1, 1), channel_mismatch=False):
main = layers.Serial(layers.BatchNorm(), layers.Relu(),
layers.Conv(channels, (3, 3), strides, padding='SAME'),
layers.BatchNorm(), layers.Relu(),
... | [
"WideResnet convolutational block."
] |
Please provide a description of the function:def WideResnet(num_blocks=3, hidden_size=64, num_output_classes=10,
mode='train'):
del mode
return layers.Serial(
layers.Conv(hidden_size, (3, 3), padding='SAME'),
WideResnetGroup(num_blocks, hidden_size),
WideResnetGroup(num_blocks, h... | [
"WideResnet from https://arxiv.org/pdf/1605.07146.pdf.\n\n Args:\n num_blocks: int, number of blocks in a group.\n hidden_size: the size of the first hidden layer (multiplied later).\n num_output_classes: int, number of classes to distinguish.\n mode: is it training or eval.\n\n Returns:\n The Wide... |
Please provide a description of the function:def GRUCell(units):
return GeneralGRUCell(
candidate_transform=lambda: core.Dense(units=units),
memory_transform=combinators.Identity,
gate_nonlinearity=core.Sigmoid,
candidate_nonlinearity=core.Tanh) | [
"Builds a traditional GRU cell with dense internal transformations.\n\n Gated Recurrent Unit paper: https://arxiv.org/abs/1412.3555\n\n\n Args:\n units: Number of hidden units.\n\n Returns:\n A Stax model representing a traditional GRU RNN cell.\n "
] |
Please provide a description of the function:def ConvGRUCell(units, kernel_size=(3, 3)):
def BuildConv():
return core.Conv(filters=units, kernel_size=kernel_size, padding='SAME')
return GeneralGRUCell(
candidate_transform=BuildConv,
memory_transform=combinators.Identity,
gate_nonlinearity... | [
"Builds a convolutional GRU.\n\n Paper: https://arxiv.org/abs/1511.06432.\n\n Args:\n units: Number of hidden units\n kernel_size: Kernel size for convolution\n\n Returns:\n A Stax model representing a GRU cell with convolution transforms.\n "
] |
Please provide a description of the function:def GeneralGRUCell(candidate_transform,
memory_transform=combinators.Identity,
gate_nonlinearity=core.Sigmoid,
candidate_nonlinearity=core.Tanh,
dropout_rate_c=0.1,
sigmoid_bias=0.... | [
"Parametrized Gated Recurrent Unit (GRU) cell construction.\n\n GRU update equations:\n $$ Update gate: u_t = \\sigmoid(U' * s_{t-1} + B') $$\n $$ Reset gate: r_t = \\sigmoid(U'' * s_{t-1} + B'') $$\n $$ Candidate memory: c_t = \\tanh(U * (r_t \\odot s_{t-1}) + B) $$\n $$ New State: s_t = u_t \\odot s_{t-1} + ... |
Please provide a description of the function:def MakeTargetMask(target, pad=0):
target_mask = (target != pad)[ :, np.newaxis, :]
target_dtype = target_mask.dtype
causal_mask = onp.tril(onp.ones((1, target.shape[-1], target.shape[-1]),
dtype=target_dtype), k=0)
target_mask = ... | [
"Create an attention mask to hide padding and future words."
] |
Please provide a description of the function:def PreparePairedSequenceBatch(source, target_in, pad=0):
target = target_in[:, :-1]
target_y = target_in[:, 1:]
source_mask = np.reshape(source != pad,
(source.shape[0], 1, 1, source.shape[-1]))
target_mask = MakeTargetMask(target, pad)... | [
"Build masks for this batch.\n\n Args:\n source: (batch, source_len) array of integer-coded symbols for inputs\n target_in: (batch, batch_len) array of integer-coded symbols for targets\n pad: int: the padding symbol used to pad the above\n\n Returns:\n Prepared batch of tuple of arrays: source, input... |
Please provide a description of the function:def _layer_norm_new_params(input_shape, rng, epsilon=1e-6): # pylint: disable=invalid-name
del rng, epsilon
features = input_shape[-1]
scale = np.ones(features)
bias = np.zeros(features)
return (scale, bias) | [
"Helper: create layer norm parameters."
] |
Please provide a description of the function:def _positional_encoding_new_params(input_shape, rng, max_len=2048): # pylint: disable=invalid-name
del rng
# Check if we are operating on chunked inputs by checking if the first
# shape is a list/tuple of shapes (otherwise it's an int or numpy array).
is_chunked... | [
"Helper: create positional encoding parameters."
] |
Please provide a description of the function:def PositionalEncoding(x, params, **unused_kwargs):
if not isinstance(x, (list, tuple)): # non-chunked inputs
symbol_size = np.shape(x)[1]
return x + params[:, :symbol_size, :]
# Chunked case: apply to all chunks selecting as much as needed.
offset = 0
re... | [
"Implements bare positional encoding."
] |
Please provide a description of the function:def DotProductAttention(query, key, value, mask, dropout, mode, rng):
depth = np.shape(query)[-1]
dots = np.matmul(query, np.swapaxes(key, -1, -2)) / np.sqrt(depth)
if mask is not None:
dots = np.where(mask, dots, -1e9)
# Softmax.
dots = np.exp(dots - backen... | [
"Core dot product self-attention.\n\n Args:\n query: array of representations\n key: array of representations\n value: array of representations\n mask: attention-mask, gates attention\n dropout: float: dropout rate\n mode: 'eval' or 'train': whether to use dropout\n rng: JAX PRNGKey: subkey fo... |
Please provide a description of the function:def PureDotProductAttention(dropout=0.0, mode='train'):
def init_fun(_, input_shapes): # pylint: disable=invalid-name
q_shape, _, v_shape, _ = input_shapes
output_shape = q_shape[:-1] + (v_shape[-1],)
return output_shape, ()
def apply_fun(params, inputs, ... | [
"Pure single-headed self-attention.\n\n Args:\n dropout: float: dropout rate\n mode: str: 'train' or 'eval'\n\n Returns:\n Pure single-headed attention layer. (No Dense transforms on input.)\n "
] |
Please provide a description of the function:def PureMultiHeadedAttention(x, params, num_heads=8, dropout=0.0,
mode='train', **kwargs):
del params
rng = kwargs.get('rng', None)
(q, k, v), mask = x
feature_depth = q.shape[-1]
assert feature_depth % num_heads == 0
head_depth = ... | [
"Pure transformer-style multi-headed attention.\n\n Args:\n x: inputs ((q, k, v), mask)\n params: parameters (none)\n num_heads: int: number of attention heads\n dropout: float: dropout rate\n mode: str: 'train' or 'eval'\n **kwargs: other arguments including the rng\n\n Returns:\n Pure Multi... |
Please provide a description of the function:def MultiHeadedAttentionQKV(
feature_depth, num_heads=8, dropout=0.0, mode='train'):
return combinators.Serial(
combinators.Parallel(
combinators.Parallel(
core.Dense(feature_depth),
core.Dense(feature_depth),
... | [
"Transformer-style multi-headed attention.\n\n Accepts inputs of the form (q, k, v), mask.\n\n Args:\n feature_depth: int: depth of embedding\n num_heads: int: number of attention heads\n dropout: float: dropout rate\n mode: str: 'train' or 'eval'\n\n Returns:\n Multi-headed self-attention layer.... |
Please provide a description of the function:def MultiHeadedAttention(
feature_depth, num_heads=8, dropout=0.0, mode='train'):
return combinators.Serial(
combinators.Parallel(
combinators.Branch(num_branches=3), # q = k = v = first input
combinators.Identity() # pass the mask
... | [
"Transformer-style multi-headed attention.\n\n Accepts inputs of the form (x, mask) and constructs (q, k, v) from x.\n\n Args:\n feature_depth: int: depth of embedding\n num_heads: int: number of attention heads\n dropout: float: dropout rate\n mode: str: 'train' or 'eval'\n\n Returns:\n Multi-he... |
Please provide a description of the function:def _chunked_selector_output_shape( # pylint: disable=invalid-name
input_shapes, selector=None, **unused_kwargs):
# Read the main function below first, the shape logic just follows the ops.
selector = selector or (lambda x: [] if x < 1 else [x-1])
triples, _ = ... | [
"Helper: calculate output shape for chunked key selector (see below)."
] |
Please provide a description of the function:def ChunkedAttentionSelector(x, params, selector=None, **kwargs):
del params, kwargs
selector = selector or (lambda x: [] if x < 1 else [x-1])
triples, masks = zip(*x)
(queries, keys, values) = zip(*triples)
result = []
for i in range(len(x)):
selected = s... | [
"Select which chunks to attend to in chunked attention.\n\n Args:\n x: inputs, a list of elements of the form (q, k, v), mask for each chunk.\n params: parameters (unused).\n selector: a function from chunk_number -> list of chunk numbers that says\n which other chunks should be appended to the given... |
Please provide a description of the function:def ChunkedCausalMultiHeadedAttention(
feature_depth, num_heads=8, dropout=0.0, chunk_selector=None, mode='train'):
prepare_attention_input = combinators.Serial(
combinators.Branch(),
combinators.Parallel(
combinators.Branch(num_branches=3), #... | [
"Transformer-style causal multi-headed attention operating on chunks.\n\n Accepts inputs that are a list of chunks and applies causal attention.\n\n Args:\n feature_depth: int: depth of embedding\n num_heads: int: number of attention heads\n dropout: float: dropout rate\n chunk_selector: a function f... |
Please provide a description of the function:def ShiftRight(x, **unused_kwargs):
if not isinstance(x, (list, tuple)): # non-chunked inputs
pad_widths = [(0, 0), (1, 0)]
padded = np.pad(x, pad_widths, mode='constant')
return padded[:, :-1]
# Handling chunked inputs. Recall that the list of chunks rep... | [
"Layer to shift the tensor to the right by padding on axis 1."
] |
Please provide a description of the function:def zipf_distribution(nbr_symbols, alpha):
tmp = np.power(np.arange(1, nbr_symbols + 1), -alpha)
zeta = np.r_[0.0, np.cumsum(tmp)]
return [x / zeta[-1] for x in zeta] | [
"Helper function: Create a Zipf distribution.\n\n Args:\n nbr_symbols: number of symbols to use in the distribution.\n alpha: float, Zipf's Law Distribution parameter. Default = 1.5.\n Usually for modelling natural text distribution is in\n the range [1.1-1.6].\n\n Returns:\n distr_map: list of... |
Please provide a description of the function:def zipf_random_sample(distr_map, sample_len):
u = np.random.random(sample_len)
# Random produces values in range [0.0,1.0); even if it is almost
# improbable(but possible) that it can generate a clear 0.000..0.
return list(np.searchsorted(distr_map, u)) | [
"Helper function: Generate a random Zipf sample of given length.\n\n Args:\n distr_map: list of float, Zipf's distribution over nbr_symbols.\n sample_len: integer, length of sequence to generate.\n\n Returns:\n sample: list of integer, Zipf's random sample over nbr_symbols.\n\n "
] |
Please provide a description of the function:def reverse_generator_nlplike(nbr_symbols,
max_length,
nbr_cases,
scale_std_dev=100,
alpha=1.5):
std_dev = max_length / scale_std_dev
distr_map = zi... | [
"Generator for the reversing nlp-like task on sequences of symbols.\n\n The length of the sequence is drawn from a Gaussian(Normal) distribution\n at random from [1, max_length] and with std deviation of 1%,\n then symbols are drawn from Zipf's law at random from [0, nbr_symbols) until\n nbr_cases sequences hav... |
Please provide a description of the function:def lower_endian_to_number(l, base):
return sum([d * (base**i) for i, d in enumerate(l)]) | [
"Helper function: convert a list of digits in the given base to a number."
] |
Please provide a description of the function:def number_to_lower_endian(n, base):
if n < base:
return [n]
return [n % base] + number_to_lower_endian(n // base, base) | [
"Helper function: convert a number to a list of digits in the given base."
] |
Please provide a description of the function:def random_number_lower_endian(length, base):
if length == 1: # Last digit can be 0 only if length is 1.
return [np.random.randint(base)]
prefix = [np.random.randint(base) for _ in range(length - 1)]
return prefix + [np.random.randint(base - 1) + 1] | [
"Helper function: generate a random number as a lower-endian digits list."
] |
Please provide a description of the function:def remote_run(cmd, instance_name, detach=False, retries=1):
if detach:
cmd = SCREEN.format(command=cmd)
args = SSH.format(instance_name=instance_name).split()
args.append(cmd)
for i in range(retries + 1):
try:
if i > 0:
tf.logging.info("Retr... | [
"Run command on GCS instance, optionally detached."
] |
Please provide a description of the function:def wait_for_ssh(ip):
for _ in range(12):
with safe_socket() as s:
try:
s.connect((ip, 22))
return True
except socket.timeout:
pass
time.sleep(10)
return False | [
"Wait for SSH to be available at given IP address."
] |
Please provide a description of the function:def launch_instance(instance_name,
command,
existing_ip=None,
cpu=1,
mem=4,
code_dir=None,
setup_command=None):
# Create instance
ip = existing_ip o... | [
"Launch a GCE instance."
] |
Please provide a description of the function:def evolved_transformer_encoder(encoder_input,
encoder_self_attention_bias,
hparams,
name="encoder",
nonpadding=None,
... | [
"Evolved Transformer encoder. See arxiv.org/abs/1901.11117 for more details.\n\n Note: Pad remover is not supported.\n\n Args:\n encoder_input: a Tensor.\n encoder_self_attention_bias: bias Tensor for self-attention (see\n common_attention.attention_bias()).\n hparams: hyperparameters for model.\n ... |
Please provide a description of the function:def evolved_transformer_decoder(decoder_input,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attention_bias,
hparams,
... | [
"Evolved Transformer decoder. See arxiv.org/abs/1901.11117 for more details.\n\n Args:\n decoder_input: a Tensor.\n encoder_output: a Tensor.\n decoder_self_attention_bias: bias Tensor for self-attention (see\n common_attention.attention_bias()).\n encoder_decoder_attention_bias: bias Tensor for e... |
Please provide a description of the function:def _add_attend_to_encoder_cache(cache, attention_name, hparams, num_layers,
key_channels, value_channels,
vars_3d_num_heads, scope_prefix,
encoder_output):
for layer in r... | [
"Add attend-to-encoder layers to cache."
] |
Please provide a description of the function:def _init_evolved_transformer_cache(cache, hparams, batch_size,
attention_init_length, encoder_output,
encoder_decoder_attention_bias,
scope_prefix):
key_channels... | [
"Create the initial cache for Evolved Transformer fast decoding."
] |
Please provide a description of the function:def add_evolved_transformer_hparams(hparams):
# Evolved Transformer "layers" are twice as deep as Transformer, so roughly
# halve the number that we use. These numbers are taken from
# arxiv.org/abs/1901.11117 .
hparams.num_encoder_layers = 3
hparams.num_decoder... | [
"Add Evolved Transformer hparams.\n\n Note: These are for the Adam optimizer, not the Adafactor optimizer used in\n the paper.\n\n Args:\n hparams: Current hparams.\n\n Returns:\n hparams updated with Evolved Transformer values.\n "
] |
Please provide a description of the function:def evolved_transformer_base_tpu():
hparams = add_evolved_transformer_hparams(transformer.transformer_tpu())
hparams.learning_rate_constant = 1 / hparams.learning_rate_warmup_steps ** 0.5
hparams.learning_rate_schedule = (
"constant*single_cycle_cos_decay")
... | [
"Base parameters for Evolved Transformer model on TPU."
] |
Please provide a description of the function:def evolved_transformer_big_tpu():
hparams = add_evolved_transformer_hparams(transformer.transformer_big_tpu())
hparams.learning_rate_constant = 1 / hparams.learning_rate_warmup_steps ** 0.5
hparams.learning_rate_schedule = (
"constant*single_cycle_cos_decay")... | [
"Big parameters for Evolved Transformer model on TPU."
] |
Please provide a description of the function:def transformer_moe_layer_v1(inputs, output_dim, hparams, train,
master_dtype=tf.bfloat16,
slice_dtype=tf.float32):
orig_inputs = inputs
input_dim = inputs.shape.dims[-1]
hidden_dim = mtf.Dimension("expert_hi... | [
"Local mixture of experts that works well on TPU.\n\n Adapted from the paper https://arxiv.org/abs/1701.06538\n\n Note: until the algorithm and inferface solidify, we pass in a hyperparameters\n dictionary in order not to complicate the interface in mtf_transformer.py .\n Once this code moves out of \"research\... |
Please provide a description of the function:def transformer_moe_layer_v2(inputs, output_dim, hparams, train,
master_dtype=tf.bfloat16, slice_dtype=tf.float32):
insert_outer_batch_dim = (len(inputs.shape.dims) == 3)
if insert_outer_batch_dim:
inputs = mtf.reshape(
inputs,... | [
"2-level mixture of experts.\n\n Adapted from the paper https://arxiv.org/abs/1701.06538\n\n Note: until the algorithm and inferface solidify, we pass in a hyperparameters\n dictionary in order not to complicate the interface in mtf_transformer.py .\n Once this code moves out of \"research\", we should pass the... |
Please provide a description of the function:def _top_2_gating(
inputs, outer_expert_dims, experts_dim, expert_capacity_dim,
hparams, train, importance=None):
group_size_dim, unused_input_dim = inputs.shape.dims[-2:]
raw_gates = mtf.softmax(mtf.layers.dense(
inputs, experts_dim, use_bias=False,
... | [
"Compute gating for mixture-of-experts in TensorFlow.\n\n Note: until the algorithm and inferface solidify, we pass in a hyperparameters\n dictionary in order not to complicate the interface in mtf_transformer.py .\n Once this code moves out of \"research\", we should pass the hyperparameters\n separately.\n\n ... |
Please provide a description of the function:def set_default_moe_hparams(hparams):
hparams.moe_num_experts = 16
hparams.moe_loss_coef = 1e-2
hparams.add_hparam("moe_gating", "top_2")
# Experts have fixed capacity per batch. We need some extra capacity
# in case gating is not perfectly balanced.
# moe_ca... | [
"Add necessary hyperparameters for mixture-of-experts."
] |
Please provide a description of the function:def _split_into_groups(n, max_group_size, mesh_dim_size):
if n % mesh_dim_size != 0:
raise ValueError(
"n=%d is not a multiple of mesh_dim_size=%d" % (n, mesh_dim_size))
num_groups = max(1, n // max_group_size)
while (num_groups % mesh_dim_size != 0 or n... | [
"Helper function for figuring out how to split a dimensino into groups.\n\n We have a dimension with size n and we want to split it into\n two dimensions: n = num_groups * group_size\n\n group_size should be the largest possible value meeting the constraints:\n group_size <= max_group_size\n (num_groups = ... |
Please provide a description of the function:def reset(self, indices=None):
return tf.cond(
tf.cast(tf.reduce_sum(indices + 1), tf.bool),
lambda: self._reset_non_empty(indices),
lambda: tf.cast(0, self.observ_dtype)) | [
"Reset the batch of environments.\n\n Args:\n indices: The batch indices of the environments to reset.\n\n Returns:\n Batch tensor of the new observations.\n "
] |
Please provide a description of the function:def adafactor_decay_rate_adam(beta2):
t = tf.to_float(tf.train.get_or_create_global_step()) + 1.0
decay = beta2 * (1.0 - tf.pow(beta2, t - 1.0)) / (1.0 - tf.pow(beta2, t))
# decay = tf.cond(tf.equal(t, 1.0), lambda: beta2, lambda: decay)
return decay | [
"Second-moment decay rate like Adam, subsuming the correction factor.\n\n Args:\n beta2: a float between 0 and 1\n Returns:\n a scalar\n "
] |
Please provide a description of the function:def adafactor_optimizer_from_hparams(hparams, lr):
if hparams.optimizer_adafactor_decay_type == "adam":
decay_rate = adafactor_decay_rate_adam(
hparams.optimizer_adafactor_beta2)
elif hparams.optimizer_adafactor_decay_type == "pow":
decay_rate = adafac... | [
"Create an Adafactor optimizer based on model hparams.\n\n Args:\n hparams: model hyperparameters\n lr: learning rate scalar.\n Returns:\n an AdafactorOptimizer\n Raises:\n ValueError: on illegal values\n "
] |
Please provide a description of the function:def _nargs_validator(nargs, message):
if message is None:
message = "Registered function must take exactly %d arguments" % nargs
def f(key, value):
del key
spec = inspect.getfullargspec(value)
if (len(spec.args) != nargs or spec.varargs is not None or... | [
"Makes validator for function to ensure it takes nargs args."
] |
Please provide a description of the function:def parse_problem_name(name):
# Recursively strip tags until we reach a base name.
if name.endswith("_rev"):
base, was_reversed, was_copy = parse_problem_name(name[:-4])
if was_reversed:
# duplicate rev
raise ValueError(
"Invalid problem ... | [
"Determines if problem_name specifies a copy and/or reversal.\n\n Args:\n name: str, problem name, possibly with suffixes.\n\n Returns:\n ProblemSpec: namedtuple with [\"base_name\", \"was_reversed\", \"was_copy\"]\n\n Raises:\n ValueError if name contains multiple suffixes of the same type\n ('_re... |
Please provide a description of the function:def get_problem_name(base_name, was_reversed=False, was_copy=False):
if any(base_name.endswith(suffix) for suffix in ("_rev", "_copy")):
raise ValueError("`base_name` cannot end in '_rev' or '_copy'")
name = base_name
if was_copy:
name = "%s_copy" % name
i... | [
"Construct a problem name from base and reversed/copy options.\n\n Inverse of `parse_problem_name`.\n\n Args:\n base_name: base problem name. Should not end in \"_rev\" or \"_copy\"\n was_reversed: if the problem is to be reversed\n was_copy: if the problem is to be copied\n\n Returns:\n string name ... |
Please provide a description of the function:def optimizer(name):
warn_msg = ("Please update `registry.optimizer` callsite "
"(likely due to a `HParams.optimizer` value)")
if name == "SGD":
name = "sgd"
tf.logging.warning("'SGD' optimizer now keyed by 'sgd'. %s" % warn_msg)
elif name == "... | [
"Get pre-registered optimizer keyed by name.\n\n `name` should be snake case, though SGD -> sgd, RMSProp -> rms_prop and\n UpperCamelCase -> snake_case conversions included for legacy support.\n\n Args:\n name: name of optimizer used in registration. This should be a snake case\n identifier, though other... |
Please provide a description of the function:def problem(problem_name, **kwargs):
spec = parse_problem_name(problem_name)
try:
return Registries.problems[spec.base_name](
was_copy=spec.was_copy, was_reversed=spec.was_reversed)
except KeyError:
# If name is not found in base problems then try cr... | [
"Get possibly copied/reversed problem in `base_registry` or `env_registry`.\n\n Args:\n problem_name: string problem name. See `parse_problem_name`.\n **kwargs: forwarded to env problem's initialize method.\n\n Returns:\n possibly reversed/copied version of base problem registered in the given\n regis... |
Please provide a description of the function:def env_problem(env_problem_name, **kwargs):
ep_cls = Registries.env_problems[env_problem_name]
ep = ep_cls()
ep.initialize(**kwargs)
return ep | [
"Get and initialize the `EnvProblem` with the given name and batch size.\n\n Args:\n env_problem_name: string name of the registered env problem.\n **kwargs: forwarded to env problem's initialize method.\n\n Returns:\n an initialized EnvProblem with the given batch size.\n "
] |
Please provide a description of the function:def display_list_by_prefix(names_list, starting_spaces=0):
cur_prefix, result_lines = None, []
space = " " * starting_spaces
for name in sorted(names_list):
split = name.split("_", 1)
prefix = split[0]
if cur_prefix != prefix:
result_lines.append(s... | [
"Creates a help string for names_list grouped by prefix."
] |
Please provide a description of the function:def help_string():
help_str =
lists = tuple(
display_list_by_prefix(entries, starting_spaces=4) for entries in [ # pylint: disable=g-complex-comprehension
list_models(),
list_hparams(),
list_ranged_hparams(),
list_base_p... | [
"Generate help string with contents of registry.",
"\nRegistry contents:\n------------------\n\n Models:\n%s\n\n HParams:\n%s\n\n RangedHParams:\n%s\n\n Problems:\n%s\n\n Optimizers:\n%s\n\n Attacks:\n%s\n\n Attack HParams:\n%s\n\n Pruning HParams:\n%s\n\n Pruning Strategies:\n%s\n\n Env Problems:\n%s\n... |
Please provide a description of the function:def validate(self, key, value):
if self._validator is not None:
self._validator(key, value) | [
"Validation function run before setting. Uses function from __init__."
] |
Please provide a description of the function:def on_set(self, key, value):
if self._on_set is not None:
self._on_set(key, value) | [
"Callback called on successful set. Uses function from __init__."
] |
Please provide a description of the function:def register(self, key_or_value=None):
def decorator(value, key):
self[key] = value
return value
# Handle if decorator was used without parens
if callable(key_or_value):
return decorator(value=key_or_value, key=None)
else:
retur... | [
"Decorator to register a function, or registration itself.\n\n This is primarily intended for use as a decorator, either with or without\n a key/parentheses.\n ```python\n @my_registry.register('key1')\n def value_fn(x, y, z):\n pass\n\n @my_registry.register()\n def another_fn(x, y):\n ... |
Please provide a description of the function:def check_dependicies(objdump_string):
GLIBC_version = re.compile(r'0{16}[ \t]+GLIBC_(\d{1,2})[.](\d{1,3})[.]?\d{,3}[ \t]+')
versions = GLIBC_version.findall(objdump_string)
assert len(versions) > 1
for major, minor in versions:
assert int(major)... | [
"Check the dynamic symbol versions.\n\n Parameters\n ----------\n objdump_string : string\n The dynamic symbol table entries of the file (result of `objdump -T` command).\n "
] |
Please provide a description of the function:def _objective_function_wrapper(func):
def inner(preds, dataset):
labels = dataset.get_label()
argc = argc_(func)
if argc == 2:
grad, hess = func(labels, preds)
elif argc == 3:
grad, hess = func(labels... | [
"Decorate an objective function.\n\n Note\n ----\n For multi-class task, the y_pred is group by class_id first, then group by row_id.\n If you want to get i-th row y_pred in j-th class, the access way is y_pred[j * num_data + i]\n and you should group grad and hess in this way as well.\n\n Paramet... |
Please provide a description of the function:def _eval_function_wrapper(func):
def inner(preds, dataset):
labels = dataset.get_label()
argc = argc_(func)
if argc == 2:
return func(labels, preds)
elif argc == 3:
return func(labels, preds, dataset.... | [
"Decorate an eval function.\n\n Note\n ----\n For multi-class task, the y_pred is group by class_id first, then group by row_id.\n If you want to get i-th row y_pred in j-th class, the access way is y_pred[j * num_data + i].\n\n Parameters\n ----------\n func : callable\n Expects a calla... |
Please provide a description of the function:def get_params(self, deep=True):
params = super(LGBMModel, self).get_params(deep=deep)
params.update(self._other_params)
return params | [
"Get parameters for this estimator.\n\n Parameters\n ----------\n deep : bool, optional (default=True)\n If True, will return the parameters for this estimator and\n contained subobjects that are estimators.\n\n Returns\n -------\n params : dict\n ... |
Please provide a description of the function:def fit(self, X, y,
sample_weight=None, init_score=None, group=None,
eval_set=None, eval_names=None, eval_sample_weight=None,
eval_class_weight=None, eval_init_score=None, eval_group=None,
eval_metric=None, early_stopping_round... | [
"Build a gradient boosting model from the training set (X, y).\n\n Parameters\n ----------\n X : array-like or sparse matrix of shape = [n_samples, n_features]\n Input feature matrix.\n y : array-like of shape = [n_samples]\n The target values (class labels in class... |
Please provide a description of the function:def predict(self, X, raw_score=False, num_iteration=None,
pred_leaf=False, pred_contrib=False, **kwargs):
if self._n_features is None:
raise LGBMNotFittedError("Estimator not fitted, call `fit` before exploiting the model.")
... | [
"Return the predicted value for each sample.\n\n Parameters\n ----------\n X : array-like or sparse matrix of shape = [n_samples, n_features]\n Input features matrix.\n raw_score : bool, optional (default=False)\n Whether to predict raw scores.\n num_iteratio... |
Please provide a description of the function:def feature_importances_(self):
if self._n_features is None:
raise LGBMNotFittedError('No feature_importances found. Need to call fit beforehand.')
return self.booster_.feature_importance(importance_type=self.importance_type) | [
"Get feature importances.\n\n Note\n ----\n Feature importance in sklearn interface used to normalize to 1,\n it's deprecated after 2.0.4 and is the same as Booster.feature_importance() now.\n ``importance_type`` attribute is passed to the function\n to configure the type o... |
Please provide a description of the function:def fit(self, X, y,
sample_weight=None, init_score=None,
eval_set=None, eval_names=None, eval_sample_weight=None,
eval_init_score=None, eval_metric=None, early_stopping_rounds=None,
verbose=True, feature_name='auto', categorica... | [
"Docstring is inherited from the LGBMModel."
] |
Please provide a description of the function:def fit(self, X, y,
sample_weight=None, init_score=None,
eval_set=None, eval_names=None, eval_sample_weight=None,
eval_class_weight=None, eval_init_score=None, eval_metric=None,
early_stopping_rounds=None, verbose=True,
... | [
"Docstring is inherited from the LGBMModel."
] |
Please provide a description of the function:def predict(self, X, raw_score=False, num_iteration=None,
pred_leaf=False, pred_contrib=False, **kwargs):
result = self.predict_proba(X, raw_score, num_iteration,
pred_leaf, pred_contrib, **kwargs)
... | [
"Docstring is inherited from the LGBMModel."
] |
Please provide a description of the function:def predict_proba(self, X, raw_score=False, num_iteration=None,
pred_leaf=False, pred_contrib=False, **kwargs):
result = super(LGBMClassifier, self).predict(X, raw_score, num_iteration,
... | [
"Return the predicted probability for each class for each sample.\n\n Parameters\n ----------\n X : array-like or sparse matrix of shape = [n_samples, n_features]\n Input features matrix.\n raw_score : bool, optional (default=False)\n Whether to predict raw scores.\... |
Please provide a description of the function:def fit(self, X, y,
sample_weight=None, init_score=None, group=None,
eval_set=None, eval_names=None, eval_sample_weight=None,
eval_init_score=None, eval_group=None, eval_metric=None,
eval_at=[1], early_stopping_rounds=None, ver... | [
"Docstring is inherited from the LGBMModel."
] |
Please provide a description of the function:def get_parameter_infos(config_hpp):
is_inparameter = False
parameter_group = None
cur_key = None
cur_info = {}
keys = []
member_infos = []
with open(config_hpp) as config_hpp_file:
for line in config_hpp_file:
if "#pragma... | [
"Parse config header file.\n\n Parameters\n ----------\n config_hpp : string\n Path to the config header file.\n\n Returns\n -------\n infos : tuple\n Tuple with names and content of sections.\n "
] |
Please provide a description of the function:def get_names(infos):
names = []
for x in infos:
for y in x:
names.append(y["name"][0])
return names | [
"Get names of all parameters.\n\n Parameters\n ----------\n infos : list\n Content of the config header file.\n\n Returns\n -------\n names : list\n Names of all parameters.\n "
] |
Please provide a description of the function:def get_alias(infos):
pairs = []
for x in infos:
for y in x:
if "alias" in y:
name = y["name"][0]
alias = y["alias"][0].split(',')
for name2 in alias:
pairs.append((name2.str... | [
"Get aliases of all parameters.\n\n Parameters\n ----------\n infos : list\n Content of the config header file.\n\n Returns\n -------\n pairs : list\n List of tuples (param alias, param name).\n "
] |
Please provide a description of the function:def set_one_var_from_string(name, param_type, checks):
ret = ""
univar_mapper = {"int": "GetInt", "double": "GetDouble", "bool": "GetBool", "std::string": "GetString"}
if "vector" not in param_type:
ret += " %s(params, \"%s\", &%s);\n" % (univar_map... | [
"Construct code for auto config file for one param value.\n\n Parameters\n ----------\n name : string\n Name of the parameter.\n param_type : string\n Type of the parameter.\n checks : list\n Constraints of the parameter.\n\n Returns\n -------\n ret : string\n Lin... |
Please provide a description of the function:def gen_parameter_description(sections, descriptions, params_rst):
def parse_check(check, reverse=False):
try:
idx = 1
float(check[idx:])
except ValueError:
idx = 2
float(check[idx:])
i... | [
"Write descriptions of parameters to the documentation file.\n\n Parameters\n ----------\n sections : list\n Names of parameters sections.\n descriptions : list\n Structured descriptions of parameters.\n params_rst : string\n Path to the file with parameters documentation.\n "... |
Please provide a description of the function:def gen_parameter_code(config_hpp, config_out_cpp):
keys, infos = get_parameter_infos(config_hpp)
names = get_names(infos)
alias = get_alias(infos)
str_to_write = r
str_to_write += "#include<LightGBM/config.h>\nnamespace LightGBM {\n"
# alias tab... | [
"Generate auto config file.\n\n Parameters\n ----------\n config_hpp : string\n Path to the config header file.\n config_out_cpp : string\n Path to the auto config file.\n\n Returns\n -------\n infos : tuple\n Tuple with names and content of sections.\n ",
"/*!\n * Cop... |
Please provide a description of the function:def _load_lib():
lib_path = find_lib_path()
if len(lib_path) == 0:
return None
lib = ctypes.cdll.LoadLibrary(lib_path[0])
lib.LGBM_GetLastError.restype = ctypes.c_char_p
return lib | [
"Load LightGBM library."
] |
Please provide a description of the function:def list_to_1d_numpy(data, dtype=np.float32, name='list'):
if is_numpy_1d_array(data):
if data.dtype == dtype:
return data
else:
return data.astype(dtype=dtype, copy=False)
elif is_1d_list(data):
return np.array(da... | [
"Convert data to 1-D numpy array."
] |
Please provide a description of the function:def cfloat32_array_to_numpy(cptr, length):
if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):
return np.fromiter(cptr, dtype=np.float32, count=length)
else:
raise RuntimeError('Expected float pointer') | [
"Convert a ctypes float pointer array to a numpy array."
] |
Please provide a description of the function:def cfloat64_array_to_numpy(cptr, length):
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') | [
"Convert a ctypes double pointer array to a numpy array."
] |
Please provide a description of the function:def cint32_array_to_numpy(cptr, length):
if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):
return np.fromiter(cptr, dtype=np.int32, count=length)
else:
raise RuntimeError('Expected int pointer') | [
"Convert a ctypes int pointer array to a numpy array."
] |
Please provide a description of the function:def cint8_array_to_numpy(cptr, length):
if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):
return np.fromiter(cptr, dtype=np.int8, count=length)
else:
raise RuntimeError('Expected int pointer') | [
"Convert a ctypes int pointer array to a numpy array."
] |
Please provide a description of the function:def param_dict_to_str(data):
if data is None or not data:
return ""
pairs = []
for key, val in data.items():
if isinstance(val, (list, tuple, set)) or is_numpy_1d_array(val):
pairs.append(str(key) + '=' + ','.join(map(str, val)))
... | [
"Convert Python dictionary to string, which is passed to C API."
] |
Please provide a description of the function:def convert_from_sliced_object(data):
if data.base is not None and isinstance(data, np.ndarray) and isinstance(data.base, np.ndarray):
if not data.flags.c_contiguous:
warnings.warn("Usage of np.ndarray subset (sliced data) is not recommended "
... | [
"Fix the memory of multi-dimensional sliced object."
] |
Please provide a description of the function:def c_float_array(data):
if is_1d_list(data):
data = np.array(data, copy=False)
if is_numpy_1d_array(data):
data = convert_from_sliced_object(data)
assert data.flags.c_contiguous
if data.dtype == np.float32:
ptr_data =... | [
"Get pointer of float numpy array / list."
] |
Please provide a description of the function:def c_int_array(data):
if is_1d_list(data):
data = np.array(data, copy=False)
if is_numpy_1d_array(data):
data = convert_from_sliced_object(data)
assert data.flags.c_contiguous
if data.dtype == np.int32:
ptr_data = dat... | [
"Get pointer of int numpy array / list."
] |
Please provide a description of the function:def predict(self, data, num_iteration=-1,
raw_score=False, pred_leaf=False, pred_contrib=False, data_has_header=False,
is_reshape=True):
if isinstance(data, Dataset):
raise TypeError("Cannot use Dataset instance fo... | [
"Predict logic.\n\n Parameters\n ----------\n data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse\n Data source for prediction.\n When data type is string, it represents the path of txt file.\n num_iteration : int, optional (default=-... |
Please provide a description of the function:def __get_num_preds(self, num_iteration, nrow, predict_type):
if nrow > MAX_INT32:
raise LightGBMError('LightGBM cannot perform prediction for data'
'with number of rows greater than MAX_INT32 (%d).\n'
... | [
"Get size of prediction result."
] |
Please provide a description of the function:def __pred_for_np2d(self, mat, num_iteration, predict_type):
if len(mat.shape) != 2:
raise ValueError('Input numpy.ndarray or list must be 2 dimensional')
def inner_predict(mat, num_iteration, predict_type, preds=None):
if ma... | [
"Predict for a 2-D numpy matrix.",
"change non-float data to float data, need to copy"
] |
Please provide a description of the function:def __pred_for_csr(self, csr, num_iteration, predict_type):
def inner_predict(csr, num_iteration, predict_type, preds=None):
nrow = len(csr.indptr) - 1
n_preds = self.__get_num_preds(num_iteration, nrow, predict_type)
if p... | [
"Predict for a CSR data."
] |
Please provide a description of the function:def __pred_for_csc(self, csc, num_iteration, predict_type):
nrow = csc.shape[0]
if nrow > MAX_INT32:
return self.__pred_for_csr(csc.tocsr(), num_iteration, predict_type)
n_preds = self.__get_num_preds(num_iteration, nrow, predict_... | [
"Predict for a CSC data."
] |
Please provide a description of the function:def __init_from_np2d(self, mat, params_str, ref_dataset):
if len(mat.shape) != 2:
raise ValueError('Input numpy.ndarray must be 2 dimensional')
self.handle = ctypes.c_void_p()
if mat.dtype == np.float32 or mat.dtype == np.float64... | [
"Initialize data from a 2-D numpy matrix."
] |
Please provide a description of the function:def __init_from_list_np2d(self, mats, params_str, ref_dataset):
ncol = mats[0].shape[1]
nrow = np.zeros((len(mats),), np.int32)
if mats[0].dtype == np.float64:
ptr_data = (ctypes.POINTER(ctypes.c_double) * len(mats))()
els... | [
"Initialize data from a list of 2-D numpy matrices."
] |
Please provide a description of the function:def __init_from_csr(self, csr, params_str, ref_dataset):
if len(csr.indices) != len(csr.data):
raise ValueError('Length mismatch: {} vs {}'.format(len(csr.indices), len(csr.data)))
self.handle = ctypes.c_void_p()
ptr_indptr, type... | [
"Initialize data from a CSR matrix."
] |
Please provide a description of the function:def __init_from_csc(self, csc, params_str, ref_dataset):
if len(csc.indices) != len(csc.data):
raise ValueError('Length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data)))
self.handle = ctypes.c_void_p()
ptr_indptr, type... | [
"Initialize data from a CSC matrix."
] |
Please provide a description of the function:def construct(self):
if self.handle is None:
if self.reference is not None:
if self.used_indices is None:
# create valid
self._lazy_init(self.data, label=self.label, reference=self.reference... | [
"Lazy init.\n\n Returns\n -------\n self : Dataset\n Constructed Dataset object.\n "
] |
Please provide a description of the function:def create_valid(self, data, label=None, weight=None, group=None,
init_score=None, silent=False, params=None):
ret = Dataset(data, label=label, reference=self,
weight=weight, group=group, init_score=init_score,
... | [
"Create validation data align with current Dataset.\n\n Parameters\n ----------\n data : string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse or list of numpy arrays\n Data source of Dataset.\n If string, it represents the path to txt file.\n l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.