Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for weight_symmetry.pruning.pruning."""
class MaskedDense(flax.deprecated.nn.Module):
"""Single-layer Dense Masked Network."""
NUM_FEATURES: int = 32
def apply(self,
inputs,
mask = None):
inputs = inputs.reshape(inputs.shape[0], -1)
<|code_end|>
. Use current file imports:
(from typing import Mapping, Optional, Sequence
from absl.testing import absltest
from rigl.experimental.jax.pruning import masked
from rigl.experimental.jax.pruning import pruning
import flax
import jax
import jax.numpy as jnp)
and context including class names, function names, or small code snippets from other files:
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
#
# Path: rigl/experimental/jax/pruning/pruning.py
# def weight_magnitude(weights):
# def prune(
# model,
# pruning_rate,
# saliency_fn = weight_magnitude,
# mask = None,
# compare_fn = jnp.greater):
. Output only the next line. | return masked.MaskedModule( |
Continue the code snippet: <|code_start|> """Tests the flax layer pruning module."""
def setUp(self):
super().setUp()
self._rng = jax.random.PRNGKey(42)
self._batch_size = 2
self._input_shape = ((self._batch_size, 28, 28, 1), jnp.float32)
self._input = jnp.ones(*self._input_shape)
_, initial_params = MaskedDense.init_by_shape(self._rng,
(self._input_shape,))
self._masked_model = flax.deprecated.nn.Model(MaskedDense, initial_params)
_, initial_params = MaskedTwoLayerDense.init_by_shape(
self._rng, (self._input_shape,))
self._masked_model_twolayer = flax.deprecated.nn.Model(
MaskedTwoLayerDense, initial_params)
_, initial_params = MaskedConv.init_by_shape(self._rng,
(self._input_shape,))
self._masked_conv_model = flax.deprecated.nn.Model(MaskedConv,
initial_params)
_, initial_params = MaskedTwoLayerConv.init_by_shape(
self._rng, (self._input_shape,))
self._masked_conv_model_twolayer = flax.deprecated.nn.Model(
MaskedTwoLayerConv, initial_params)
def test_prune_single_layer_dense_no_mask(self):
"""Tests pruning of single dense layer without an existing mask."""
<|code_end|>
. Use current file imports:
from typing import Mapping, Optional, Sequence
from absl.testing import absltest
from rigl.experimental.jax.pruning import masked
from rigl.experimental.jax.pruning import pruning
import flax
import jax
import jax.numpy as jnp
and context (classes, functions, or code) from other files:
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
#
# Path: rigl/experimental/jax/pruning/pruning.py
# def weight_magnitude(weights):
# def prune(
# model,
# pruning_rate,
# saliency_fn = weight_magnitude,
# mask = None,
# compare_fn = jnp.greater):
. Output only the next line. | pruned_mask = pruning.prune(self._masked_model, 0.5) |
Using the snippet: <|code_start|>
class TrainingTest(absltest.TestCase):
"""Tests functions for training loop and training convenience functions."""
def setUp(self):
super().setUp()
self._batch_size = 128 # Note: Tests are run on GPU/TPU.
self._batch_size_test = 128
self._shuffle_buffer_size = 1024
self._rng = jax.random.PRNGKey(42)
self._input_shape = ((self._batch_size, 28, 28, 1), jnp.float32)
self._num_classes = 10
self._num_epochs = 1
self._learning_rate_fn = lambda _: 0.01
self._weight_decay = 0.0001
self._momentum = 0.9
self._rng = jax.random.PRNGKey(42)
self._min_loss = jnp.finfo(float).eps
self._max_loss = 2.0 * math.log(self._num_classes)
self._dataset_name = 'MNIST'
self._model_name = 'MNIST_CNN'
self._summarywriter = tensorboard.SummaryWriter('/tmp/')
<|code_end|>
, determine the next line of code. You have imports:
import functools
import math
import flax
import jax
import jax.numpy as jnp
from absl.testing import absltest
from flax import jax_utils
from flax.metrics import tensorboard
from flax.training import common_utils
from rigl.experimental.jax.datasets import dataset_factory
from rigl.experimental.jax.models import model_factory
from rigl.experimental.jax.training import training
and context (class names, function names, or code) available:
# Path: rigl/experimental/jax/datasets/dataset_factory.py
# DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
# 'MNIST': mnist.MNISTDataset,
# 'CIFAR10': cifar10.CIFAR10Dataset,
# }
# def create_dataset(name, *args, **kwargs):
#
# Path: rigl/experimental/jax/models/model_factory.py
# MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
# 'MNIST_CNN': mnist_cnn.MNISTCNN,
# 'MNIST_FC': mnist_fc.MNISTFC,
# 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
# }
# def create_model(
# name, rng,
# input_specs, **kwargs
# ):
# def update_model(model,
# **kwargs):
#
# Path: rigl/experimental/jax/training/training.py
# LABELKEY = dataset_base.ImageDataset.LABELKEY
# DATAKEY = dataset_base.ImageDataset.DATAKEY
# def _shard_batch(xs):
# def _prepare(x):
# def train_step(
# optimizer: flax.optim.Optimizer, batch: Mapping[str, jnp.array],
# rng: Callable[[int], jnp.array], state: flax.deprecated.nn.Collection,
# learning_rate_fn: Callable[[int], float]
# ) -> Tuple[flax.optim.Optimizer, flax.deprecated.nn.Collection, float, float]:
# def loss_fn(
# model: flax.deprecated.nn.Model
# ) -> Tuple[float, Tuple[flax.deprecated.nn.Collection, jnp.array]]:
# def __init__(
# self,
# optimizer_def: flax.optim.OptimizerDef,
# initial_model: flax.deprecated.nn.Model,
# initial_state: flax.deprecated.nn.Collection,
# dataset: jnp.array,
# rng: Callable[[int], jnp.array] = None,
# summary_writer: Optional[tf.summary.SummaryWriter] = None,
# ):
# class Trainer:
. Output only the next line. | self._dataset = dataset_factory.create_dataset( |
Given the following code snippet before the placeholder: <|code_start|> def setUp(self):
super().setUp()
self._batch_size = 128 # Note: Tests are run on GPU/TPU.
self._batch_size_test = 128
self._shuffle_buffer_size = 1024
self._rng = jax.random.PRNGKey(42)
self._input_shape = ((self._batch_size, 28, 28, 1), jnp.float32)
self._num_classes = 10
self._num_epochs = 1
self._learning_rate_fn = lambda _: 0.01
self._weight_decay = 0.0001
self._momentum = 0.9
self._rng = jax.random.PRNGKey(42)
self._min_loss = jnp.finfo(float).eps
self._max_loss = 2.0 * math.log(self._num_classes)
self._dataset_name = 'MNIST'
self._model_name = 'MNIST_CNN'
self._summarywriter = tensorboard.SummaryWriter('/tmp/')
self._dataset = dataset_factory.create_dataset(
self._dataset_name,
self._batch_size,
self._batch_size_test,
shuffle_buffer_size=self._shuffle_buffer_size)
<|code_end|>
, predict the next line using imports from the current file:
import functools
import math
import flax
import jax
import jax.numpy as jnp
from absl.testing import absltest
from flax import jax_utils
from flax.metrics import tensorboard
from flax.training import common_utils
from rigl.experimental.jax.datasets import dataset_factory
from rigl.experimental.jax.models import model_factory
from rigl.experimental.jax.training import training
and context including class names, function names, and sometimes code from other files:
# Path: rigl/experimental/jax/datasets/dataset_factory.py
# DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
# 'MNIST': mnist.MNISTDataset,
# 'CIFAR10': cifar10.CIFAR10Dataset,
# }
# def create_dataset(name, *args, **kwargs):
#
# Path: rigl/experimental/jax/models/model_factory.py
# MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
# 'MNIST_CNN': mnist_cnn.MNISTCNN,
# 'MNIST_FC': mnist_fc.MNISTFC,
# 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
# }
# def create_model(
# name, rng,
# input_specs, **kwargs
# ):
# def update_model(model,
# **kwargs):
#
# Path: rigl/experimental/jax/training/training.py
# LABELKEY = dataset_base.ImageDataset.LABELKEY
# DATAKEY = dataset_base.ImageDataset.DATAKEY
# def _shard_batch(xs):
# def _prepare(x):
# def train_step(
# optimizer: flax.optim.Optimizer, batch: Mapping[str, jnp.array],
# rng: Callable[[int], jnp.array], state: flax.deprecated.nn.Collection,
# learning_rate_fn: Callable[[int], float]
# ) -> Tuple[flax.optim.Optimizer, flax.deprecated.nn.Collection, float, float]:
# def loss_fn(
# model: flax.deprecated.nn.Model
# ) -> Tuple[float, Tuple[flax.deprecated.nn.Collection, jnp.array]]:
# def __init__(
# self,
# optimizer_def: flax.optim.OptimizerDef,
# initial_model: flax.deprecated.nn.Model,
# initial_state: flax.deprecated.nn.Collection,
# dataset: jnp.array,
# rng: Callable[[int], jnp.array] = None,
# summary_writer: Optional[tf.summary.SummaryWriter] = None,
# ):
# class Trainer:
. Output only the next line. | self._model, self._state = model_factory.create_model( |
Predict the next line after this snippet: <|code_start|> self._dataset_name = 'MNIST'
self._model_name = 'MNIST_CNN'
self._summarywriter = tensorboard.SummaryWriter('/tmp/')
self._dataset = dataset_factory.create_dataset(
self._dataset_name,
self._batch_size,
self._batch_size_test,
shuffle_buffer_size=self._shuffle_buffer_size)
self._model, self._state = model_factory.create_model(
self._model_name,
self._rng, (self._input_shape,),
num_classes=self._num_classes)
self._optimizer = flax.optim.Momentum(
learning_rate=self._learning_rate_fn(0),
beta=self._momentum,
weight_decay=self._weight_decay)
def test_train_one_step(self):
"""Tests training loop over one step."""
iterator = self._dataset.get_train()
batch = next(iterator)
state = jax_utils.replicate(self._state)
optimizer = jax_utils.replicate(self._optimizer.create(self._model))
self._rng, step_key = jax.random.split(self._rng)
<|code_end|>
using the current file's imports:
import functools
import math
import flax
import jax
import jax.numpy as jnp
from absl.testing import absltest
from flax import jax_utils
from flax.metrics import tensorboard
from flax.training import common_utils
from rigl.experimental.jax.datasets import dataset_factory
from rigl.experimental.jax.models import model_factory
from rigl.experimental.jax.training import training
and any relevant context from other files:
# Path: rigl/experimental/jax/datasets/dataset_factory.py
# DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
# 'MNIST': mnist.MNISTDataset,
# 'CIFAR10': cifar10.CIFAR10Dataset,
# }
# def create_dataset(name, *args, **kwargs):
#
# Path: rigl/experimental/jax/models/model_factory.py
# MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
# 'MNIST_CNN': mnist_cnn.MNISTCNN,
# 'MNIST_FC': mnist_fc.MNISTFC,
# 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
# }
# def create_model(
# name, rng,
# input_specs, **kwargs
# ):
# def update_model(model,
# **kwargs):
#
# Path: rigl/experimental/jax/training/training.py
# LABELKEY = dataset_base.ImageDataset.LABELKEY
# DATAKEY = dataset_base.ImageDataset.DATAKEY
# def _shard_batch(xs):
# def _prepare(x):
# def train_step(
# optimizer: flax.optim.Optimizer, batch: Mapping[str, jnp.array],
# rng: Callable[[int], jnp.array], state: flax.deprecated.nn.Collection,
# learning_rate_fn: Callable[[int], float]
# ) -> Tuple[flax.optim.Optimizer, flax.deprecated.nn.Collection, float, float]:
# def loss_fn(
# model: flax.deprecated.nn.Model
# ) -> Tuple[float, Tuple[flax.deprecated.nn.Collection, jnp.array]]:
# def __init__(
# self,
# optimizer_def: flax.optim.OptimizerDef,
# initial_model: flax.deprecated.nn.Model,
# initial_state: flax.deprecated.nn.Collection,
# dataset: jnp.array,
# rng: Callable[[int], jnp.array] = None,
# summary_writer: Optional[tf.summary.SummaryWriter] = None,
# ):
# class Trainer:
. Output only the next line. | batch = training._shard_batch(batch) |
Predict the next line after this snippet: <|code_start|> # there is a type conflict in passing iterators of different types to
# itertools.chain.
counts = [
count_permutations_mask_layer(layer, next_layer)
for layer, next_layer in utils.pairwise_longest(mask.values())
]
sum_stats = {}
for key in sum_keys:
sum_stats[key] = functools.reduce(operator.add, (z[key] for z in counts))
product_stats = {}
for key in product_keys:
product_stats[key] = functools.reduce(operator.mul,
(z[key] for z in counts))
return {**sum_stats, **product_stats}
def get_mask_stats(mask):
"""Calculates an array of mask statistics.
Args:
mask: A model mask to calculate the statistics of.
Returns:
A dictionary, containing a set of mask statistics.
"""
mask_stats = count_permutations_mask(mask)
mask_stats.update({
<|code_end|>
using the current file's imports:
import functools
import math
import operator
import jax.numpy as jnp
import numpy as np
from typing import Dict, Optional, Union
from rigl.experimental.jax.pruning import masked
from rigl.experimental.jax.utils import utils
and any relevant context from other files:
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
#
# Path: rigl/experimental/jax/utils/utils.py
# def cross_entropy_loss(log_softmax_logits,
# labels):
# def compute_metrics(logits,
# labels):
# def _np_converter(obj):
# def dump_dict_json(data_dict, path):
# def count_param(model,
# param_names):
# def cosine_similarity(a, b):
# def param_as_array(params):
# def cosine_similarity_model(initial_model,
# current_model):
# def vector_difference_norm_model(initial_model,
# current_model):
# def pairwise_longest(iterable):
# T = TypeVar('T')
. Output only the next line. | 'sparsity': masked.mask_sparsity(mask), |
Given the following code snippet before the placeholder: <|code_start|> mask_stats['zeroed_neurons'] = int(zeroed_count)
mask_stats['permutations'] = functools.reduce(
operator.mul, (np.math.factorial(t) for t in unique_counts))
mask_stats['unique_neurons'] = len(unique_counts)
return mask_stats
def count_permutations_mask(mask):
"""Calculates the number of permutations for a given model mask.
Args:
mask: Model masks to check, similar to Model.params.
Returns:
A dictionary with stats on the permutation structure of a mask, including
the number of symmetric permutations of the mask, number of unique mask
columns, count of the zeroed out (structurally pruned) neurons, and total
number of neurons/filters.
"""
sum_keys = ('total_neurons', 'unique_neurons', 'zeroed_neurons')
product_keys = ('permutations',)
# Count permutation stats for each pairwise set of layers.
# Note: I tried doing this with more_itertools.pairwise/itertools.chain, but
# there is a type conflict in passing iterators of different types to
# itertools.chain.
counts = [
count_permutations_mask_layer(layer, next_layer)
<|code_end|>
, predict the next line using imports from the current file:
import functools
import math
import operator
import jax.numpy as jnp
import numpy as np
from typing import Dict, Optional, Union
from rigl.experimental.jax.pruning import masked
from rigl.experimental.jax.utils import utils
and context including class names, function names, and sometimes code from other files:
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
#
# Path: rigl/experimental/jax/utils/utils.py
# def cross_entropy_loss(log_softmax_logits,
# labels):
# def compute_metrics(logits,
# labels):
# def _np_converter(obj):
# def dump_dict_json(data_dict, path):
# def count_param(model,
# param_names):
# def cosine_similarity(a, b):
# def param_as_array(params):
# def cosine_similarity_model(initial_model,
# current_model):
# def vector_difference_norm_model(initial_model,
# current_model):
# def pairwise_longest(iterable):
# T = TypeVar('T')
. Output only the next line. | for layer, next_layer in utils.pairwise_longest(mask.values()) |
Using the snippet: <|code_start|> initial_params)
def _create_logits_labels(self, correct):
"""Creates a set of logits/labels resulting from correct classification.
Args:
correct: If true, creates labels for a correct classifiction, otherwise
creates labels for an incorrect classification.
Returns:
A tuple of logits, labels.
"""
logits = np.full((self._batch_size, self._num_classes),
(1.0 - self._true_logit) / self._num_classes,
dtype=np.float32)
# Diagonal over batch will be true.
for i in range(self._batch_size):
logits[i, i % self._num_classes] = self._true_logit
labels = np.zeros(self._batch_size, dtype=jnp.int32)
# Diagonal over batch will be true.
for i in range(self._batch_size):
labels[i] = (i if correct else i + 1) % self._num_classes
return jnp.array(logits), jnp.array(labels)
def test_compute_metrics_correct(self):
"""Tests output when logit outputs indicate correct classification."""
logits, labels_correct = self._create_logits_labels(True)
<|code_end|>
, determine the next line of code. You have imports:
import functools
import json
import operator
import tempfile
import flax
import jax
import jax.numpy as jnp
import numpy as np
from typing import Optional, Sequence, TypeVar
from absl.testing import absltest
from absl.testing import parameterized
from rigl.experimental.jax.training import training
from rigl.experimental.jax.utils import utils
and context (class names, function names, or code) available:
# Path: rigl/experimental/jax/training/training.py
# LABELKEY = dataset_base.ImageDataset.LABELKEY
# DATAKEY = dataset_base.ImageDataset.DATAKEY
# def _shard_batch(xs):
# def _prepare(x):
# def train_step(
# optimizer: flax.optim.Optimizer, batch: Mapping[str, jnp.array],
# rng: Callable[[int], jnp.array], state: flax.deprecated.nn.Collection,
# learning_rate_fn: Callable[[int], float]
# ) -> Tuple[flax.optim.Optimizer, flax.deprecated.nn.Collection, float, float]:
# def loss_fn(
# model: flax.deprecated.nn.Model
# ) -> Tuple[float, Tuple[flax.deprecated.nn.Collection, jnp.array]]:
# def __init__(
# self,
# optimizer_def: flax.optim.OptimizerDef,
# initial_model: flax.deprecated.nn.Model,
# initial_state: flax.deprecated.nn.Collection,
# dataset: jnp.array,
# rng: Callable[[int], jnp.array] = None,
# summary_writer: Optional[tf.summary.SummaryWriter] = None,
# ):
# class Trainer:
#
# Path: rigl/experimental/jax/utils/utils.py
# def cross_entropy_loss(log_softmax_logits,
# labels):
# def compute_metrics(logits,
# labels):
# def _np_converter(obj):
# def dump_dict_json(data_dict, path):
# def count_param(model,
# param_names):
# def cosine_similarity(a, b):
# def param_as_array(params):
# def cosine_similarity_model(initial_model,
# current_model):
# def vector_difference_norm_model(initial_model,
# current_model):
# def pairwise_longest(iterable):
# T = TypeVar('T')
. Output only the next line. | logits = training._shard_batch(logits) |
Continue the code snippet: <|code_start|> """Creates a set of logits/labels resulting from correct classification.
Args:
correct: If true, creates labels for a correct classifiction, otherwise
creates labels for an incorrect classification.
Returns:
A tuple of logits, labels.
"""
logits = np.full((self._batch_size, self._num_classes),
(1.0 - self._true_logit) / self._num_classes,
dtype=np.float32)
# Diagonal over batch will be true.
for i in range(self._batch_size):
logits[i, i % self._num_classes] = self._true_logit
labels = np.zeros(self._batch_size, dtype=jnp.int32)
# Diagonal over batch will be true.
for i in range(self._batch_size):
labels[i] = (i if correct else i + 1) % self._num_classes
return jnp.array(logits), jnp.array(labels)
def test_compute_metrics_correct(self):
"""Tests output when logit outputs indicate correct classification."""
logits, labels_correct = self._create_logits_labels(True)
logits = training._shard_batch(logits)
labels_correct = training._shard_batch(labels_correct)
<|code_end|>
. Use current file imports:
import functools
import json
import operator
import tempfile
import flax
import jax
import jax.numpy as jnp
import numpy as np
from typing import Optional, Sequence, TypeVar
from absl.testing import absltest
from absl.testing import parameterized
from rigl.experimental.jax.training import training
from rigl.experimental.jax.utils import utils
and context (classes, functions, or code) from other files:
# Path: rigl/experimental/jax/training/training.py
# LABELKEY = dataset_base.ImageDataset.LABELKEY
# DATAKEY = dataset_base.ImageDataset.DATAKEY
# def _shard_batch(xs):
# def _prepare(x):
# def train_step(
# optimizer: flax.optim.Optimizer, batch: Mapping[str, jnp.array],
# rng: Callable[[int], jnp.array], state: flax.deprecated.nn.Collection,
# learning_rate_fn: Callable[[int], float]
# ) -> Tuple[flax.optim.Optimizer, flax.deprecated.nn.Collection, float, float]:
# def loss_fn(
# model: flax.deprecated.nn.Model
# ) -> Tuple[float, Tuple[flax.deprecated.nn.Collection, jnp.array]]:
# def __init__(
# self,
# optimizer_def: flax.optim.OptimizerDef,
# initial_model: flax.deprecated.nn.Model,
# initial_state: flax.deprecated.nn.Collection,
# dataset: jnp.array,
# rng: Callable[[int], jnp.array] = None,
# summary_writer: Optional[tf.summary.SummaryWriter] = None,
# ):
# class Trainer:
#
# Path: rigl/experimental/jax/utils/utils.py
# def cross_entropy_loss(log_softmax_logits,
# labels):
# def compute_metrics(logits,
# labels):
# def _np_converter(obj):
# def dump_dict_json(data_dict, path):
# def count_param(model,
# param_names):
# def cosine_similarity(a, b):
# def param_as_array(params):
# def cosine_similarity_model(initial_model,
# current_model):
# def vector_difference_norm_model(initial_model,
# current_model):
# def pairwise_longest(iterable):
# T = TypeVar('T')
. Output only the next line. | p_compute_metrics = jax.pmap(utils.compute_metrics, axis_name='batch') |
Here is a snippet: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""CIFAR10 Dataset.
Dataset abstraction/factory to allow us to easily use tensorflow datasets (TFDS)
with JAX/FLAX, by defining a bunch of wrappers, including preprocessing.
In this case, the CIFAR10 dataset.
"""
<|code_end|>
. Write the next line using the current file imports:
from typing import MutableMapping, Sequence
from rigl.experimental.jax.datasets import dataset_base
import tensorflow.compat.v2 as tf
and context from other files:
# Path: rigl/experimental/jax/datasets/dataset_base.py
# class Dataset(metaclass=abc.ABCMeta):
# class ImageDataset(Dataset):
# DATAKEY: Optional[str] = None
# LABELKEY: str = 'label'
# DATAKEY = 'image'
# def __init__(self,
# name,
# batch_size,
# batch_size_test,
# shuffle_buffer_size,
# prefetch_size = 1,
# seed = None): # pytype: disable=annotation-type-mismatch
# def _dataset_dir(self):
# def get_train(self):
# def get_train_len(self):
# def get_test(self):
# def get_test_len(self):
# def preprocess(
# self, data):
# def augment(
# self, data):
# def preprocess(
# self, data):
, which may include functions, classes, or code. Output only the next line. | class CIFAR10Dataset(dataset_base.ImageDataset): |
Predict the next line after this snippet: <|code_start|># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for weight_symmetry.pruning.masked."""
class Dense(flax.deprecated.nn.Module):
"""Single-layer Dense Non-Masked Network."""
NUM_FEATURES: int = 32
def apply(self, inputs):
inputs = inputs.reshape(inputs.shape[0], -1)
return flax.deprecated.nn.Dense(inputs, features=self.NUM_FEATURES)
class MaskedDense(flax.deprecated.nn.Module):
"""Single-layer Dense Masked Network."""
NUM_FEATURES: int = 32
def apply(self,
inputs,
mask = None):
inputs = inputs.reshape(inputs.shape[0], -1)
<|code_end|>
using the current file's imports:
from typing import Mapping, Optional, Sequence
from absl.testing import absltest
from absl.testing import parameterized
from rigl.experimental.jax.pruning import masked
import flax
import jax
import jax.numpy as jnp
import numpy as np
and any relevant context from other files:
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
. Output only the next line. | return masked.MaskedModule( |
Based on the snippet: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""MNIST Dataset.
Dataset abstraction/factory to allow us to easily use tensorflow datasets (TFDS)
with JAX/FLAX, by defining a bunch of wrappers, including preprocessing.
In this case, the MNIST dataset.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from typing import MutableMapping
from rigl.experimental.jax.datasets import dataset_base
import tensorflow.compat.v2 as tf
and context (classes, functions, sometimes code) from other files:
# Path: rigl/experimental/jax/datasets/dataset_base.py
# class Dataset(metaclass=abc.ABCMeta):
# class ImageDataset(Dataset):
# DATAKEY: Optional[str] = None
# LABELKEY: str = 'label'
# DATAKEY = 'image'
# def __init__(self,
# name,
# batch_size,
# batch_size_test,
# shuffle_buffer_size,
# prefetch_size = 1,
# seed = None): # pytype: disable=annotation-type-mismatch
# def _dataset_dir(self):
# def get_train(self):
# def get_train_len(self):
# def get_test(self):
# def get_test_len(self):
# def preprocess(
# self, data):
# def augment(
# self, data):
# def preprocess(
# self, data):
. Output only the next line. | class MNISTDataset(dataset_base.ImageDataset): |
Predict the next line for this snippet: <|code_start|># Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for weight_symmetry.train."""
class TrainTest(absltest.TestCase):
def test_train_driver_run(self):
"""Tests that the training driver runs, and outputs a TF summary."""
experiment_dir = tempfile.mkdtemp()
eval_flags = dict(
epochs=1,
experiment_dir=experiment_dir,
)
with flagsaver.flagsaver(**eval_flags):
<|code_end|>
with the help of current file imports:
import glob
import tempfile
from os import path
from absl.testing import absltest
from absl.testing import flagsaver
from rigl.experimental.jax import train
and context from other files:
# Path: rigl/experimental/jax/train.py
# FLAGS = flags.FLAGS
# MODEL_LIST: Sequence[str] = tuple(model_factory.MODELS.keys())
# DATASET_LIST: Sequence[str] = tuple(dataset_factory.DATASETS.keys())
# def run_training():
# def main(argv):
, which may contain function names, class names, or code. Output only the next line. | train.main([]) |
Here is a snippet: <|code_start|> Returns:
An `Operation` that applies the specified gradients. If `global_step`
was not None, that operation also increments `global_step`.
"""
def apply_gradient_op():
return self._optimizer.apply_gradients(
grads_and_vars, global_step=global_step, name=name)
maybe_reduce = lambda x: x
if self._use_tpu:
maybe_reduce = tpu_ops.cross_replica_sum
grads_and_vars_dict = {
re.findall('(.+)/weights:0', var.name)[0]: (maybe_reduce(grad), var)
for grad, var in grads_and_vars
if var.name.endswith('weights:0')
}
def snip_fn(mask, sparsity, dtype):
"""Creates a random sparse mask with deterministic sparsity.
Args:
mask: tf.Tensor, used to obtain correct corresponding gradient.
sparsity: float, between 0 and 1.
dtype: tf.dtype, type of the return value.
Returns:
tf.Tensor
"""
del dtype
<|code_end|>
. Write the next line using the current file imports:
import re
import numpy as np
import six
from rigl import sparse_utils
from tensorflow.contrib.model_pruning.python import pruning
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import stateless_random_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.tpu.ops import tpu_ops
from tensorflow.python.training import learning_rate_decay
from tensorflow.python.training import moving_averages
from tensorflow.python.training import optimizer as tf_optimizer
from tensorflow.python.training import training_util
and context from other files:
# Path: rigl/sparse_utils.py
# DEFAULT_ERK_SCALE = 1.0
# def mask_extract_name_fn(mask_name):
# def get_n_zeros(size, sparsity):
# def calculate_sparsity(masks):
# def get_mask_random_numpy(mask_shape, sparsity, random_state=None):
# def get_mask_random(mask, sparsity, dtype, random_state=None):
# def get_sparsities_erdos_renyi(all_masks,
# default_sparsity,
# custom_sparsity_map,
# include_kernel,
# extract_name_fn=mask_extract_name_fn,
# erk_power_scale=DEFAULT_ERK_SCALE):
# def get_sparsities_uniform(all_masks,
# default_sparsity,
# custom_sparsity_map,
# extract_name_fn=mask_extract_name_fn):
# def get_sparsities_str(all_masks, default_sparsity):
# def get_sparsities(all_masks,
# method,
# default_sparsity,
# custom_sparsity_map,
# extract_name_fn=mask_extract_name_fn,
# erk_power_scale=DEFAULT_ERK_SCALE):
# def get_mask_init_fn(all_masks,
# method,
# default_sparsity,
# custom_sparsity_map,
# mask_fn=get_mask_random,
# erk_power_scale=DEFAULT_ERK_SCALE,
# extract_name_fn=mask_extract_name_fn):
# def _get_kernel(layer):
# def get_stats(masked_layers,
# default_sparsity=0.8,
# method='erdos_renyi',
# custom_sparsities=None,
# is_debug=False,
# width=1.,
# first_layer_name='conv1',
# last_layer_name='conv_preds',
# param_size=32,
# erk_power_scale=DEFAULT_ERK_SCALE):
, which may include functions, classes, or code. Output only the next line. | var_name = sparse_utils.mask_extract_name_fn(mask.name) |
Predict the next line for this snippet: <|code_start|> loaded_mask = l_source.pruning_vars[0][1]
if shuffle_mask:
# tf shuffle shuffles along the first dim, so we need to flatten.
loaded_mask = tf.reshape(
tf.random.shuffle(tf.reshape(loaded_mask, -1)), loaded_mask.shape)
mask.assign(loaded_mask)
n_active = tf.reduce_sum(mask)
n_dense = tf.cast(tf.size(mask), dtype=n_active.dtype)
logging.info('After: %s, %.2f', l_target.name,
(n_active / n_dense).numpy())
del mask_init_model
if weight_init_path:
logging.info('Loading weights from: %s', weight_init_path)
weight_init_model = tf.keras.models.clone_model(model)
ckpt = tf.train.Checkpoint(model=weight_init_model)
ckpt.restore(weight_init_path)
for l_source, l_target in zip(weight_init_model.layers, model.layers):
for var_source, var_target in zip(l_source.trainable_variables,
l_target.trainable_variables):
var_target.assign(var_source)
logging.info('Weight %s loaded from ckpt.', var_target.name)
del weight_init_model
elif weight_init_method == 'unit_scaled':
logging.info('Using unit_scaled initialization.')
for layer in model.layers:
if isinstance(layer, PRUNING_WRAPPER):
# TODO following the outcome of b/148083099, update following.
# Add the weight, mask and the valid dimensions.
weight = layer.weights[0]
mask = layer.weights[2]
<|code_end|>
with the help of current file imports:
import functools
import gin
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
from typing import Optional, Tuple
from absl import flags
from absl import logging
from rigl.rigl_tf2 import init_utils
from rigl.rigl_tf2 import networks
from tensorflow_model_optimization.python.core.sparsity.keras import pruning_schedule
from tensorflow_model_optimization.python.core.sparsity.keras import pruning_wrapper
and context from other files:
# Path: rigl/rigl_tf2/init_utils.py
# def unit_scaled_init(mask, method='fanavg_uniform', scale=1.0):
# def layer_scaled_init(mask, method='fanavg_uniform', scale=1.0):
# def unit_scaled_init_tf1(mask,
# method='fanavg_uniform',
# scale=1.0,
# dtype=tf.float32):
# def new_val_fn(index):
#
# Path: rigl/rigl_tf2/networks.py
# def lenet5(input_shape,
# num_classes,
# activation,
# kernel_regularizer,
# use_batch_norm = False,
# hidden_sizes = (6, 16, 120, 84)):
# def maybe_add_batchnorm():
# def mlp(input_shape,
# num_classes,
# activation,
# kernel_regularizer,
# use_batch_norm = False,
# hidden_sizes = (300, 100)):
# def maybe_add_batchnorm():
, which may contain function names, class names, or code. Output only the next line. | new_init = init_utils.unit_scaled_init(mask) |
Predict the next line for this snippet: <|code_start|> else:
raise ValueError('Mode: %s, is not valid' % mode)
return p_params
# Forked from tensorflow_model_optimization/python/core/sparsity/keras/prune.py
def maybe_prune_layer(layer, params, filter_fn):
if filter_fn(layer):
return PRUNING_WRAPPER(layer, **params)
return layer
@gin.configurable('network')
def get_network(
pruning_params,
input_shape,
num_classes,
activation = 'relu',
network_name = 'lenet5',
mask_init_path = None,
shuffle_mask = False,
weight_init_path = None,
weight_init_method = None,
weight_decay = 0.,
noise_stddev = 0.,
pruned_layer_types = PRUNED_LAYER_TYPES):
"""Creates the network."""
kernel_regularizer = (
tf.keras.regularizers.l2(weight_decay) if (weight_decay > 0) else None)
# (1) Create keras model.
<|code_end|>
with the help of current file imports:
import functools
import gin
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
from typing import Optional, Tuple
from absl import flags
from absl import logging
from rigl.rigl_tf2 import init_utils
from rigl.rigl_tf2 import networks
from tensorflow_model_optimization.python.core.sparsity.keras import pruning_schedule
from tensorflow_model_optimization.python.core.sparsity.keras import pruning_wrapper
and context from other files:
# Path: rigl/rigl_tf2/init_utils.py
# def unit_scaled_init(mask, method='fanavg_uniform', scale=1.0):
# def layer_scaled_init(mask, method='fanavg_uniform', scale=1.0):
# def unit_scaled_init_tf1(mask,
# method='fanavg_uniform',
# scale=1.0,
# dtype=tf.float32):
# def new_val_fn(index):
#
# Path: rigl/rigl_tf2/networks.py
# def lenet5(input_shape,
# num_classes,
# activation,
# kernel_regularizer,
# use_batch_norm = False,
# hidden_sizes = (6, 16, 120, 84)):
# def maybe_add_batchnorm():
# def mlp(input_shape,
# num_classes,
# activation,
# kernel_regularizer,
# use_batch_norm = False,
# hidden_sizes = (300, 100)):
# def maybe_add_batchnorm():
, which may contain function names, class names, or code. Output only the next line. | model = getattr(networks, network_name)( |
Given the code snippet: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Weight Symmetry: Train Model.
Trains a model from scratch, saving the relevant early weight snapshots.
"""
FLAGS = flags.FLAGS
MODEL_LIST: Sequence[str] = tuple(model_factory.MODELS.keys())
<|code_end|>
, generate the next line using the imports in this file:
import ast
import uuid
import flax
import jax
import jax.numpy as np
from os import path
from typing import List, Sequence
from absl import app
from absl import flags
from absl import logging
from flax.metrics import tensorboard
from flax.training import lr_schedule
from rigl.experimental.jax.datasets import dataset_factory
from rigl.experimental.jax.models import model_factory
from rigl.experimental.jax.training import training
and context (functions, classes, or occasionally code) from other files:
# Path: rigl/experimental/jax/datasets/dataset_factory.py
# DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
# 'MNIST': mnist.MNISTDataset,
# 'CIFAR10': cifar10.CIFAR10Dataset,
# }
# def create_dataset(name, *args, **kwargs):
#
# Path: rigl/experimental/jax/models/model_factory.py
# MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
# 'MNIST_CNN': mnist_cnn.MNISTCNN,
# 'MNIST_FC': mnist_fc.MNISTFC,
# 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
# }
# def create_model(
# name, rng,
# input_specs, **kwargs
# ):
# def update_model(model,
# **kwargs):
#
# Path: rigl/experimental/jax/training/training.py
# LABELKEY = dataset_base.ImageDataset.LABELKEY
# DATAKEY = dataset_base.ImageDataset.DATAKEY
# def _shard_batch(xs):
# def _prepare(x):
# def train_step(
# optimizer: flax.optim.Optimizer, batch: Mapping[str, jnp.array],
# rng: Callable[[int], jnp.array], state: flax.deprecated.nn.Collection,
# learning_rate_fn: Callable[[int], float]
# ) -> Tuple[flax.optim.Optimizer, flax.deprecated.nn.Collection, float, float]:
# def loss_fn(
# model: flax.deprecated.nn.Model
# ) -> Tuple[float, Tuple[flax.deprecated.nn.Collection, jnp.array]]:
# def __init__(
# self,
# optimizer_def: flax.optim.OptimizerDef,
# initial_model: flax.deprecated.nn.Model,
# initial_state: flax.deprecated.nn.Collection,
# dataset: jnp.array,
# rng: Callable[[int], jnp.array] = None,
# summary_writer: Optional[tf.summary.SummaryWriter] = None,
# ):
# class Trainer:
. Output only the next line. | DATASET_LIST: Sequence[str] = tuple(dataset_factory.DATASETS.keys()) |
Using the snippet: <|code_start|> FLAGS.model,
rng, ((input_shape, np.float32),),
num_classes=dataset.num_classes)
if FLAGS.optimizer == 'Adam':
optimizer = flax.optim.Adam(
learning_rate=FLAGS.lr, weight_decay=FLAGS.weight_decay)
elif FLAGS.optimizer == 'Momentum':
optimizer = flax.optim.Momentum(
learning_rate=FLAGS.lr,
beta=FLAGS.momentum,
weight_decay=FLAGS.weight_decay,
nesterov=False)
steps_per_epoch = dataset.get_train_len() // FLAGS.batch_size
if FLAGS.lr_schedule == 'constant':
lr_fn = lr_schedule.create_constant_learning_rate_schedule(
FLAGS.lr, steps_per_epoch)
elif FLAGS.lr_schedule == 'stepped':
lr_schedule_steps = ast.literal_eval(FLAGS.lr_schedule_steps)
lr_fn = lr_schedule.create_stepped_learning_rate_schedule(
FLAGS.lr, steps_per_epoch, lr_schedule_steps)
elif FLAGS.lr_schedule == 'cosine':
lr_fn = lr_schedule.create_cosine_learning_rate_schedule(
FLAGS.lr, steps_per_epoch, FLAGS.epochs)
else:
raise ValueError('Unknown LR schedule type {}'.format(FLAGS.lr_schedule))
if jax.host_id() == 0:
<|code_end|>
, determine the next line of code. You have imports:
import ast
import uuid
import flax
import jax
import jax.numpy as np
from os import path
from typing import List, Sequence
from absl import app
from absl import flags
from absl import logging
from flax.metrics import tensorboard
from flax.training import lr_schedule
from rigl.experimental.jax.datasets import dataset_factory
from rigl.experimental.jax.models import model_factory
from rigl.experimental.jax.training import training
and context (class names, function names, or code) available:
# Path: rigl/experimental/jax/datasets/dataset_factory.py
# DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
# 'MNIST': mnist.MNISTDataset,
# 'CIFAR10': cifar10.CIFAR10Dataset,
# }
# def create_dataset(name, *args, **kwargs):
#
# Path: rigl/experimental/jax/models/model_factory.py
# MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
# 'MNIST_CNN': mnist_cnn.MNISTCNN,
# 'MNIST_FC': mnist_fc.MNISTFC,
# 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
# }
# def create_model(
# name, rng,
# input_specs, **kwargs
# ):
# def update_model(model,
# **kwargs):
#
# Path: rigl/experimental/jax/training/training.py
# LABELKEY = dataset_base.ImageDataset.LABELKEY
# DATAKEY = dataset_base.ImageDataset.DATAKEY
# def _shard_batch(xs):
# def _prepare(x):
# def train_step(
# optimizer: flax.optim.Optimizer, batch: Mapping[str, jnp.array],
# rng: Callable[[int], jnp.array], state: flax.deprecated.nn.Collection,
# learning_rate_fn: Callable[[int], float]
# ) -> Tuple[flax.optim.Optimizer, flax.deprecated.nn.Collection, float, float]:
# def loss_fn(
# model: flax.deprecated.nn.Model
# ) -> Tuple[float, Tuple[flax.deprecated.nn.Collection, jnp.array]]:
# def __init__(
# self,
# optimizer_def: flax.optim.OptimizerDef,
# initial_model: flax.deprecated.nn.Model,
# initial_state: flax.deprecated.nn.Collection,
# dataset: jnp.array,
# rng: Callable[[int], jnp.array] = None,
# summary_writer: Optional[tf.summary.SummaryWriter] = None,
# ):
# class Trainer:
. Output only the next line. | trainer = training.Trainer( |
Here is a snippet: <|code_start|>
Returns:
A tensor of shape (batch, num_classes), containing the logit output.
Raises:
ValueError if the number of pooling layers is too many for the given input
size, or if the provided mask is not of the correct depth for the model.
"""
# Note: First dim is batch, last dim is channels, other dims are "spatial".
if not all([(dim >= 2**(len(filters)//2)) for dim in inputs.shape[1:-2]]):
raise ValueError(
'Input spatial size, {}, does not allow {} pooling layers.'.format(
str(inputs.shape[1:-2]), len(filters))
)
depth = 1 + len(filters)
masks = masked.generate_model_masks(depth, masks,
masked_layer_indices)
batch_norm = flax.deprecated.nn.BatchNorm.partial(
use_running_average=not train, momentum=0.99, epsilon=1e-5)
for i, filter_num in enumerate(filters):
if f'MaskedModule_{i}' in masks:
logging.info('Layer %d is masked in model', i)
mask = masks[f'MaskedModule_{i}']
inputs = masked.masked(flax.deprecated.nn.Conv, mask)(
inputs,
features=filter_num,
kernel_size=filter_shape,
<|code_end|>
. Write the next line using the current file imports:
from typing import Callable, Mapping, Optional, Sequence
from absl import logging
from rigl.experimental.jax.pruning import init
from rigl.experimental.jax.pruning import masked
import flax
import jax.numpy as jnp
and context from other files:
# Path: rigl/experimental/jax/pruning/init.py
# def init(rng, shape, dtype=dtype):
# if mask is None:
# return base_init(rng, shape, dtype)
#
# # Find the ablated neurons in the mask, to determine correct fan_out.
# neuron_weight_count = jnp.sum(
# jnp.reshape(mask, (-1, mask.shape[-1])), axis=0)
# non_zero_neurons = jnp.sum(neuron_weight_count != 0)
#
# # Special case of completely ablated weight matrix/layer.
# if jnp.sum(non_zero_neurons) == 0:
# print('Empty weight mask!')
# return jnp.zeros(shape, dtype)
#
# # Neurons have different fan_in w/mask, build up initialization per-unit.
# init_cols = []
# rng, *split_rngs = jax.random.split(rng, mask.shape[-1] + 1)
# for i in range(mask.shape[-1]):
# # Special case of ablated neuron.
# if neuron_weight_count[i] == 0:
# init_cols.append(jnp.zeros(shape[:-1] + (1,), dtype))
# continue
#
# # Fake shape of weight matrix with correct fan_in, and fan_out.
# sparse_shape = (int(neuron_weight_count[i]), int(non_zero_neurons))
#
# # Use only the first column of init from initializer, since faked fan_out.
# init = base_init(split_rngs[i], sparse_shape, dtype)[Ellipsis, 0]
#
# # Expand out to full sparse array.
# expanded_init = jnp.zeros(
# mask[Ellipsis, i].shape,
# dtype).flatten().at[jnp.where(mask[Ellipsis, i].flatten() == 1)].set(init)
# expanded_init = jnp.reshape(expanded_init, mask[Ellipsis, i].shape)
# init_cols.append(expanded_init[Ellipsis, jnp.newaxis])
#
# return jnp.concatenate(init_cols, axis=-1)
#
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
, which may include functions, classes, or code. Output only the next line. | kernel_init=init.sparse_init( |
Next line prediction: <|code_start|> """Applies a convolution to the inputs.
Args:
inputs: Input data with dimensions (batch, spatial_dims..., features).
num_classes: Number of classes in the dataset.
filter_shape: Shape of the convolutional filters.
filters: Number of filters in each convolutional layer, and number of conv
layers (given by length of sequence).
init_fn: Initialization function used for convolutional layers.
train: If model is being evaluated in training mode or not.
activation_fn: Activation function to be used for convolutional layers.
masks: Masks of the layers in this model, in the same form as
module params, or None.
masked_layer_indices: The layer indices of layers in model to be masked.
Returns:
A tensor of shape (batch, num_classes), containing the logit output.
Raises:
ValueError if the number of pooling layers is too many for the given input
size, or if the provided mask is not of the correct depth for the model.
"""
# Note: First dim is batch, last dim is channels, other dims are "spatial".
if not all([(dim >= 2**(len(filters)//2)) for dim in inputs.shape[1:-2]]):
raise ValueError(
'Input spatial size, {}, does not allow {} pooling layers.'.format(
str(inputs.shape[1:-2]), len(filters))
)
depth = 1 + len(filters)
<|code_end|>
. Use current file imports:
(from typing import Callable, Mapping, Optional, Sequence
from absl import logging
from rigl.experimental.jax.pruning import init
from rigl.experimental.jax.pruning import masked
import flax
import jax.numpy as jnp)
and context including class names, function names, or small code snippets from other files:
# Path: rigl/experimental/jax/pruning/init.py
# def init(rng, shape, dtype=dtype):
# if mask is None:
# return base_init(rng, shape, dtype)
#
# # Find the ablated neurons in the mask, to determine correct fan_out.
# neuron_weight_count = jnp.sum(
# jnp.reshape(mask, (-1, mask.shape[-1])), axis=0)
# non_zero_neurons = jnp.sum(neuron_weight_count != 0)
#
# # Special case of completely ablated weight matrix/layer.
# if jnp.sum(non_zero_neurons) == 0:
# print('Empty weight mask!')
# return jnp.zeros(shape, dtype)
#
# # Neurons have different fan_in w/mask, build up initialization per-unit.
# init_cols = []
# rng, *split_rngs = jax.random.split(rng, mask.shape[-1] + 1)
# for i in range(mask.shape[-1]):
# # Special case of ablated neuron.
# if neuron_weight_count[i] == 0:
# init_cols.append(jnp.zeros(shape[:-1] + (1,), dtype))
# continue
#
# # Fake shape of weight matrix with correct fan_in, and fan_out.
# sparse_shape = (int(neuron_weight_count[i]), int(non_zero_neurons))
#
# # Use only the first column of init from initializer, since faked fan_out.
# init = base_init(split_rngs[i], sparse_shape, dtype)[Ellipsis, 0]
#
# # Expand out to full sparse array.
# expanded_init = jnp.zeros(
# mask[Ellipsis, i].shape,
# dtype).flatten().at[jnp.where(mask[Ellipsis, i].flatten() == 1)].set(init)
# expanded_init = jnp.reshape(expanded_init, mask[Ellipsis, i].shape)
# init_cols.append(expanded_init[Ellipsis, jnp.newaxis])
#
# return jnp.concatenate(init_cols, axis=-1)
#
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
. Output only the next line. | masks = masked.generate_model_masks(depth, masks, |
Predict the next line for this snippet: <|code_start|>
tf.reset_default_graph()
g = tf.Graph()
with g.as_default():
test_inputs, test_labels = self.get_next()
with self.test_session() as sess:
test_images_out, test_labels_out = sess.run([test_inputs, test_labels])
self.assertAllEqual(test_images_out.shape, [BATCH_SIZE, 32, 32, 3])
self.assertAllEqual(test_labels_out.shape, [BATCH_SIZE])
@parameterized.parameters(
{
'training_method': 'baseline',
},
{
'training_method': 'threshold',
},
{
'training_method': 'rigl',
},
)
def testTrainingStep(self, training_method):
tf.reset_default_graph()
g = tf.Graph()
with g.as_default():
images, labels = self.get_next()
<|code_end|>
with the help of current file imports:
import os
import absl.testing.parameterized as parameterized
import tensorflow.compat.v1 as tf
from absl import flags
from absl import logging
from rigl.cifar_resnet import resnet_train_eval
from rigl.cifar_resnet.data_helper import input_fn
from tensorflow.contrib.model_pruning.python import pruning
and context from other files:
# Path: rigl/cifar_resnet/resnet_train_eval.py
# FLAGS = flags.FLAGS
# PARAM_SUFFIXES = ('gamma', 'beta', 'weights', 'biases')
# MASK_SUFFIX = 'mask'
# CLASSES = [
# 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse',
# 'ship', 'truck'
# ]
# def create_eval_metrics(labels, logits):
# def train_fn(training_method, global_step, total_loss, train_dir, accuracy,
# top_5_accuracy):
# def build_model(mode,
# images,
# labels,
# training_method='baseline',
# num_classes=10,
# depth=10,
# width=4):
# def wide_resnet_w_pruning(features, labels, mode, params):
# def init_fn(scaffold, session):
# def main(argv):
#
# Path: rigl/cifar_resnet/data_helper.py
# def input_fn(params):
# """Provides batches of CIFAR data.
#
# Args:
# params: A dictionary with a set of arguments, namely:
# * batch_size (int32), specifies data points in a batch
# * data_split (string), designates train or eval
# * data_dictionary (string), specifies directory location of input dataset
#
# Returns:
# images: A float32`Tensor` of size [batch_size, 32, 32, 3].
# labels: A int32`Tensor` of size [batch_size, num_classes].
# """
#
# def parse_serialized_example(record):
# """Parses a CIFAR10 example."""
# image = record['image']
# label = tf.cast(record['label'], tf.int32)
# image = tf.cast(image, tf.float32)
# image = tf.image.per_image_standardization(image)
# if data_split == 'train':
# image = preprocess_train(image, IMG_SIZE, IMG_SIZE)
# return image, label
#
# data_split = params['data_split']
# batch_size = params['batch_size']
# if data_split == 'eval':
# data_split = 'test'
# dataset = tfds.load('cifar10:3.*.*', split=data_split)
#
# # we only repeat an example and shuffle inputs during training
# if data_split == 'train':
# dataset = dataset.repeat().shuffle(buffer_size=50000)
#
# # deserialize record into tensors and apply pre-processing.
# dataset = dataset.map(parse_serialized_example).prefetch(batch_size)
#
# # at test time, for the final batch we drop remaining examples so that no
# # example is seen twice.
# dataset = dataset.batch(batch_size)
#
# images_batch, labels_batch = tf.data.make_one_shot_iterator(
# dataset).get_next()
#
# return (tf.reshape(images_batch, [batch_size, IMG_SIZE, IMG_SIZE, 3]),
# tf.reshape(labels_batch, [batch_size]))
, which may contain function names, class names, or code. Output only the next line. | global_step, _, _, logits = resnet_train_eval.build_model( |
Using the snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
r"""Tests for the data_helper input pipeline and the training process.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
FLAGS = flags.FLAGS
BATCH_SIZE = 1
NUM_IMAGES = 1
JITTER_MULTIPLIER = 2
class DataHelperTest(tf.test.TestCase, parameterized.TestCase):
def get_next(self):
data_directory = FLAGS.data_directory
# we pass the updated eval and train string to the params dictionary.
params = {
'mode': 'test',
'data_split': 'eval',
'batch_size': BATCH_SIZE,
'data_directory': data_directory
}
<|code_end|>
, determine the next line of code. You have imports:
import os
import absl.testing.parameterized as parameterized
import tensorflow.compat.v1 as tf
from absl import flags
from absl import logging
from rigl.cifar_resnet import resnet_train_eval
from rigl.cifar_resnet.data_helper import input_fn
from tensorflow.contrib.model_pruning.python import pruning
and context (class names, function names, or code) available:
# Path: rigl/cifar_resnet/resnet_train_eval.py
# FLAGS = flags.FLAGS
# PARAM_SUFFIXES = ('gamma', 'beta', 'weights', 'biases')
# MASK_SUFFIX = 'mask'
# CLASSES = [
# 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse',
# 'ship', 'truck'
# ]
# def create_eval_metrics(labels, logits):
# def train_fn(training_method, global_step, total_loss, train_dir, accuracy,
# top_5_accuracy):
# def build_model(mode,
# images,
# labels,
# training_method='baseline',
# num_classes=10,
# depth=10,
# width=4):
# def wide_resnet_w_pruning(features, labels, mode, params):
# def init_fn(scaffold, session):
# def main(argv):
#
# Path: rigl/cifar_resnet/data_helper.py
# def input_fn(params):
# """Provides batches of CIFAR data.
#
# Args:
# params: A dictionary with a set of arguments, namely:
# * batch_size (int32), specifies data points in a batch
# * data_split (string), designates train or eval
# * data_dictionary (string), specifies directory location of input dataset
#
# Returns:
# images: A float32`Tensor` of size [batch_size, 32, 32, 3].
# labels: A int32`Tensor` of size [batch_size, num_classes].
# """
#
# def parse_serialized_example(record):
# """Parses a CIFAR10 example."""
# image = record['image']
# label = tf.cast(record['label'], tf.int32)
# image = tf.cast(image, tf.float32)
# image = tf.image.per_image_standardization(image)
# if data_split == 'train':
# image = preprocess_train(image, IMG_SIZE, IMG_SIZE)
# return image, label
#
# data_split = params['data_split']
# batch_size = params['batch_size']
# if data_split == 'eval':
# data_split = 'test'
# dataset = tfds.load('cifar10:3.*.*', split=data_split)
#
# # we only repeat an example and shuffle inputs during training
# if data_split == 'train':
# dataset = dataset.repeat().shuffle(buffer_size=50000)
#
# # deserialize record into tensors and apply pre-processing.
# dataset = dataset.map(parse_serialized_example).prefetch(batch_size)
#
# # at test time, for the final batch we drop remaining examples so that no
# # example is seen twice.
# dataset = dataset.batch(batch_size)
#
# images_batch, labels_batch = tf.data.make_one_shot_iterator(
# dataset).get_next()
#
# return (tf.reshape(images_batch, [batch_size, IMG_SIZE, IMG_SIZE, 3]),
# tf.reshape(labels_batch, [batch_size]))
. Output only the next line. | test_inputs, test_labels = input_fn(params) |
Given snippet: <|code_start|># http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the data_helper input pipeline and the training process.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class GetMaskRandomTest(tf.test.TestCase, parameterized.TestCase):
def _setup_session(self):
"""Resets the graph and returns a fresh session."""
tf.reset_default_graph()
sess = tf.Session()
return sess
@parameterized.parameters(((30, 40), 0.5), ((1, 2, 1, 4), 0.8), ((3,), 0.1))
def testMaskConnectionDeterminism(self, shape, sparsity):
sess = self._setup_session()
mask = tf.ones(shape)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import absl.testing.parameterized as parameterized
import numpy as np
import tensorflow.compat.v1 as tf
from rigl import sparse_utils
and context:
# Path: rigl/sparse_utils.py
# DEFAULT_ERK_SCALE = 1.0
# def mask_extract_name_fn(mask_name):
# def get_n_zeros(size, sparsity):
# def calculate_sparsity(masks):
# def get_mask_random_numpy(mask_shape, sparsity, random_state=None):
# def get_mask_random(mask, sparsity, dtype, random_state=None):
# def get_sparsities_erdos_renyi(all_masks,
# default_sparsity,
# custom_sparsity_map,
# include_kernel,
# extract_name_fn=mask_extract_name_fn,
# erk_power_scale=DEFAULT_ERK_SCALE):
# def get_sparsities_uniform(all_masks,
# default_sparsity,
# custom_sparsity_map,
# extract_name_fn=mask_extract_name_fn):
# def get_sparsities_str(all_masks, default_sparsity):
# def get_sparsities(all_masks,
# method,
# default_sparsity,
# custom_sparsity_map,
# extract_name_fn=mask_extract_name_fn,
# erk_power_scale=DEFAULT_ERK_SCALE):
# def get_mask_init_fn(all_masks,
# method,
# default_sparsity,
# custom_sparsity_map,
# mask_fn=get_mask_random,
# erk_power_scale=DEFAULT_ERK_SCALE,
# extract_name_fn=mask_extract_name_fn):
# def _get_kernel(layer):
# def get_stats(masked_layers,
# default_sparsity=0.8,
# method='erdos_renyi',
# custom_sparsities=None,
# is_debug=False,
# width=1.,
# first_layer_name='conv1',
# last_layer_name='conv_preds',
# param_size=32,
# erk_power_scale=DEFAULT_ERK_SCALE):
which might include code, classes, or functions. Output only the next line. | mask1 = sparse_utils.get_mask_random(mask, sparsity, tf.int32) |
Next line prediction: <|code_start|>#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for weight_symmetry.random_mask."""
class RandomMaskTest(absltest.TestCase):
def test_run_fc(self):
"""Test random mask driver with fully-connected model."""
experiment_dir = tempfile.mkdtemp()
self._eval_flags = dict(
epochs=1,
experiment_dir=experiment_dir,
model='MNIST_FC',
)
with flagsaver.flagsaver(**self._eval_flags):
<|code_end|>
. Use current file imports:
(import glob
import tempfile
from os import path
from absl.testing import absltest
from absl.testing import flagsaver
from rigl.experimental.jax import random_mask)
and context including class names, function names, or small code snippets from other files:
# Path: rigl/experimental/jax/random_mask.py
# def main(argv: List[str]):
. Output only the next line. | random_mask.main([]) |
Continue the code snippet: <|code_start|>
def weight_magnitude(weights):
"""Creates weight magnitude-based saliencies, given a weight matrix."""
return jnp.absolute(weights)
def prune(
model,
pruning_rate,
saliency_fn = weight_magnitude,
mask = None,
compare_fn = jnp.greater):
"""Returns a mask for a model where the params in each layer are pruned using a saliency function.
Args:
model: The model to create a pruning mask for.
pruning_rate: The fraction of lowest magnitude saliency weights that are
pruned. If a float, the same rate is used for all layers, otherwise if it
is a mapping, it must contain a rate for all masked layers in the model.
saliency_fn: A function that returns a float number used to rank
the importance of individual weights in the layer.
mask: If the model has an existing mask, the mask will be applied before
pruning the model.
compare_fn: A pairwise operator to compare saliency with threshold, and
return True if the saliency indicates the value should not be masked.
Returns:
A pruned mask for the given model.
"""
if not mask:
<|code_end|>
. Use current file imports:
import collections
import flax
import jax.numpy as jnp
from typing import Any, Callable, Mapping, Optional, Union
from rigl.experimental.jax.pruning import masked
and context (classes, functions, or code) from other files:
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
. Output only the next line. | mask = masked.simple_mask(model, jnp.ones, masked.WEIGHT_PARAM_NAMES) |
Predict the next line after this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for weight_symmetry.prune."""
class PruneTest(absltest.TestCase):
def test_prune_fixed_schedule(self):
"""Tests training/pruning driver with a fixed global sparsity."""
experiment_dir = self.create_tempdir().full_path
eval_flags = dict(
epochs=1,
pruning_rate=0.95,
experiment_dir=experiment_dir,
)
with flagsaver.flagsaver(**eval_flags):
<|code_end|>
using the current file's imports:
import glob
from os import path
from absl.testing import absltest
from absl.testing import flagsaver
from rigl.experimental.jax import prune
and any relevant context from other files:
# Path: rigl/experimental/jax/prune.py
# def main(argv: List[str]):
. Output only the next line. | prune.main([]) |
Given snippet: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Common training code.
This module contains utility functions for training NN.
Attributes:
LABELKEY: The key used to retrieve a label from the batch dictionary.
DATAKEY: The key used to retrieve an input image from the batch dictionary.
PruningRateFnType: Typing alias for a valid pruning rate function.
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import collections
import functools
import time
import flax
import jax
import jax.numpy as jnp
import tensorflow.compat.v2 as tf
from typing import Callable, Dict, Mapping, Optional, Tuple, Union
from absl import logging
from flax import jax_utils
from flax.training import common_utils
from rigl.experimental.jax.datasets import dataset_base
from rigl.experimental.jax.models import model_factory
from rigl.experimental.jax.pruning import masked
from rigl.experimental.jax.pruning import pruning
from rigl.experimental.jax.pruning import symmetry
from rigl.experimental.jax.utils import utils
and context:
# Path: rigl/experimental/jax/datasets/dataset_base.py
# class Dataset(metaclass=abc.ABCMeta):
# class ImageDataset(Dataset):
# DATAKEY: Optional[str] = None
# LABELKEY: str = 'label'
# DATAKEY = 'image'
# def __init__(self,
# name,
# batch_size,
# batch_size_test,
# shuffle_buffer_size,
# prefetch_size = 1,
# seed = None): # pytype: disable=annotation-type-mismatch
# def _dataset_dir(self):
# def get_train(self):
# def get_train_len(self):
# def get_test(self):
# def get_test_len(self):
# def preprocess(
# self, data):
# def augment(
# self, data):
# def preprocess(
# self, data):
#
# Path: rigl/experimental/jax/models/model_factory.py
# MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
# 'MNIST_CNN': mnist_cnn.MNISTCNN,
# 'MNIST_FC': mnist_fc.MNISTFC,
# 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
# }
# def create_model(
# name, rng,
# input_specs, **kwargs
# ):
# def update_model(model,
# **kwargs):
#
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
#
# Path: rigl/experimental/jax/pruning/pruning.py
# def weight_magnitude(weights):
# def prune(
# model,
# pruning_rate,
# saliency_fn = weight_magnitude,
# mask = None,
# compare_fn = jnp.greater):
#
# Path: rigl/experimental/jax/pruning/symmetry.py
# def count_permutations_mask_layer(
# mask_layer,
# next_mask_layer = None,
# parameter_key = 'kernel'):
# def count_permutations_mask(mask):
# def get_mask_stats(mask):
#
# Path: rigl/experimental/jax/utils/utils.py
# def cross_entropy_loss(log_softmax_logits,
# labels):
# def compute_metrics(logits,
# labels):
# def _np_converter(obj):
# def dump_dict_json(data_dict, path):
# def count_param(model,
# param_names):
# def cosine_similarity(a, b):
# def param_as_array(params):
# def cosine_similarity_model(initial_model,
# current_model):
# def vector_difference_norm_model(initial_model,
# current_model):
# def pairwise_longest(iterable):
# T = TypeVar('T')
which might include code, classes, or functions. Output only the next line. | LABELKEY = dataset_base.ImageDataset.LABELKEY |
Predict the next line after this snippet: <|code_start|> dataset: The training dataset.
rng: Random number generator, i.e. jax.random.PRNGKey, to use for model
training, e.g. dropout.
summary_writer: An optional tensorboard summary writer for logging
self._rng = rng
if self._rng is None:
self._rng = jax.random.PRNGKey(42)
def _update_optimizer(self, model: flax.deprecated.nn.Model):
"""Updates the optimizer based on the given model."""
self.optimizer = jax_utils.replicate(
self._optimizer_def.create(model))
def train(
self,
num_epochs: int,
lr_fn: Optional[Callable[[int], float]] = None,
pruning_rate_fn: Optional[PruningRateFnType] = None,
update_iter: int = 100,
update_epoch: int = 10
) -> Tuple[flax.deprecated.nn.Model, Mapping[str, Union[int, float, Mapping[
str, float]]]]:
"""Trains the model over the given number of epochs.
Args:
num_epochs: The total number of epochs to train over.
lr_fn: The learning rate function, takes the current iteration/step as an
argument and returns the current learning rate, uses constant learning
rate if no function is provided.
<|code_end|>
using the current file's imports:
import collections
import functools
import time
import flax
import jax
import jax.numpy as jnp
import tensorflow.compat.v2 as tf
from typing import Callable, Dict, Mapping, Optional, Tuple, Union
from absl import logging
from flax import jax_utils
from flax.training import common_utils
from rigl.experimental.jax.datasets import dataset_base
from rigl.experimental.jax.models import model_factory
from rigl.experimental.jax.pruning import masked
from rigl.experimental.jax.pruning import pruning
from rigl.experimental.jax.pruning import symmetry
from rigl.experimental.jax.utils import utils
and any relevant context from other files:
# Path: rigl/experimental/jax/datasets/dataset_base.py
# class Dataset(metaclass=abc.ABCMeta):
# class ImageDataset(Dataset):
# DATAKEY: Optional[str] = None
# LABELKEY: str = 'label'
# DATAKEY = 'image'
# def __init__(self,
# name,
# batch_size,
# batch_size_test,
# shuffle_buffer_size,
# prefetch_size = 1,
# seed = None): # pytype: disable=annotation-type-mismatch
# def _dataset_dir(self):
# def get_train(self):
# def get_train_len(self):
# def get_test(self):
# def get_test_len(self):
# def preprocess(
# self, data):
# def augment(
# self, data):
# def preprocess(
# self, data):
#
# Path: rigl/experimental/jax/models/model_factory.py
# MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
# 'MNIST_CNN': mnist_cnn.MNISTCNN,
# 'MNIST_FC': mnist_fc.MNISTFC,
# 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
# }
# def create_model(
# name, rng,
# input_specs, **kwargs
# ):
# def update_model(model,
# **kwargs):
#
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
#
# Path: rigl/experimental/jax/pruning/pruning.py
# def weight_magnitude(weights):
# def prune(
# model,
# pruning_rate,
# saliency_fn = weight_magnitude,
# mask = None,
# compare_fn = jnp.greater):
#
# Path: rigl/experimental/jax/pruning/symmetry.py
# def count_permutations_mask_layer(
# mask_layer,
# next_mask_layer = None,
# parameter_key = 'kernel'):
# def count_permutations_mask(mask):
# def get_mask_stats(mask):
#
# Path: rigl/experimental/jax/utils/utils.py
# def cross_entropy_loss(log_softmax_logits,
# labels):
# def compute_metrics(logits,
# labels):
# def _np_converter(obj):
# def dump_dict_json(data_dict, path):
# def count_param(model,
# param_names):
# def cosine_similarity(a, b):
# def param_as_array(params):
# def cosine_similarity_model(initial_model,
# current_model):
# def vector_difference_norm_model(initial_model,
# current_model):
# def pairwise_longest(iterable):
# T = TypeVar('T')
. Output only the next line. | pruning_rate_fn: The pruning rate function, takes the current epoch as an |
Predict the next line for this snippet: <|code_start|>) -> Tuple[flax.optim.Optimizer, flax.deprecated.nn.Collection, float, float]:
"""Performs training for one minibatch.
Args:
optimizer: Optimizer to use.
batch: Minibatch to train with.
rng: Random number generator, i.e. jax.random.PRNGKey, to use for model
training, e.g. dropout.
state: Model state.
learning_rate_fn: A function that returns the learning rate given the step.
Returns:
A tuple consisting of the new optimizer, new state, mini-batch loss, and
gradient norm.
"""
def loss_fn(
model: flax.deprecated.nn.Model
) -> Tuple[float, Tuple[flax.deprecated.nn.Collection, jnp.array]]:
"""Evaluates the loss function.
Args:
model: The model with which to evaluate the loss.
Returns:
Tuple of the loss for the mini-batch, and model state.
"""
with flax.deprecated.nn.stateful(state) as new_state:
with flax.deprecated.nn.stochastic(rng):
logits = model(batch[DATAKEY])
<|code_end|>
with the help of current file imports:
import collections
import functools
import time
import flax
import jax
import jax.numpy as jnp
import tensorflow.compat.v2 as tf
from typing import Callable, Dict, Mapping, Optional, Tuple, Union
from absl import logging
from flax import jax_utils
from flax.training import common_utils
from rigl.experimental.jax.datasets import dataset_base
from rigl.experimental.jax.models import model_factory
from rigl.experimental.jax.pruning import masked
from rigl.experimental.jax.pruning import pruning
from rigl.experimental.jax.pruning import symmetry
from rigl.experimental.jax.utils import utils
and context from other files:
# Path: rigl/experimental/jax/datasets/dataset_base.py
# class Dataset(metaclass=abc.ABCMeta):
# class ImageDataset(Dataset):
# DATAKEY: Optional[str] = None
# LABELKEY: str = 'label'
# DATAKEY = 'image'
# def __init__(self,
# name,
# batch_size,
# batch_size_test,
# shuffle_buffer_size,
# prefetch_size = 1,
# seed = None): # pytype: disable=annotation-type-mismatch
# def _dataset_dir(self):
# def get_train(self):
# def get_train_len(self):
# def get_test(self):
# def get_test_len(self):
# def preprocess(
# self, data):
# def augment(
# self, data):
# def preprocess(
# self, data):
#
# Path: rigl/experimental/jax/models/model_factory.py
# MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
# 'MNIST_CNN': mnist_cnn.MNISTCNN,
# 'MNIST_FC': mnist_fc.MNISTFC,
# 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
# }
# def create_model(
# name, rng,
# input_specs, **kwargs
# ):
# def update_model(model,
# **kwargs):
#
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
#
# Path: rigl/experimental/jax/pruning/pruning.py
# def weight_magnitude(weights):
# def prune(
# model,
# pruning_rate,
# saliency_fn = weight_magnitude,
# mask = None,
# compare_fn = jnp.greater):
#
# Path: rigl/experimental/jax/pruning/symmetry.py
# def count_permutations_mask_layer(
# mask_layer,
# next_mask_layer = None,
# parameter_key = 'kernel'):
# def count_permutations_mask(mask):
# def get_mask_stats(mask):
#
# Path: rigl/experimental/jax/utils/utils.py
# def cross_entropy_loss(log_softmax_logits,
# labels):
# def compute_metrics(logits,
# labels):
# def _np_converter(obj):
# def dump_dict_json(data_dict, path):
# def count_param(model,
# param_names):
# def cosine_similarity(a, b):
# def param_as_array(params):
# def cosine_similarity_model(initial_model,
# current_model):
# def vector_difference_norm_model(initial_model,
# current_model):
# def pairwise_longest(iterable):
# T = TypeVar('T')
, which may contain function names, class names, or code. Output only the next line. | loss = utils.cross_entropy_loss(logits, batch[LABELKEY]) |
Next line prediction: <|code_start|>
NUM_FEATURES: int = 32
def apply(self,
inputs,
mask = None):
inputs = inputs.reshape(inputs.shape[0], -1)
return masked.MaskedModule(
inputs,
features=self.NUM_FEATURES,
wrapped_module=flax.deprecated.nn.Dense,
mask=mask['MaskedModule_0'] if mask else None)
class MaskFactoryTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self._rng = jax.random.PRNGKey(42)
self._input_shape = ((1, 28, 28, 1), jnp.float32)
self._num_classes = 10
self._sparsity = 0.9
_, initial_params = MaskedDense.init_by_shape(self._rng,
(self._input_shape,))
# Use the same initialization for both masked/unmasked models.
self._model = flax.deprecated.nn.Model(MaskedDense, initial_params)
def _create_mask(self, mask_type):
<|code_end|>
. Use current file imports:
(from typing import Mapping, Optional
from absl.testing import absltest
from absl.testing import parameterized
from rigl.experimental.jax.pruning import mask_factory
from rigl.experimental.jax.pruning import masked
import flax
import jax
import jax.numpy as jnp)
and context including class names, function names, or small code snippets from other files:
# Path: rigl/experimental/jax/pruning/mask_factory.py
# MASK_TYPES: Mapping[str, MaskFnType] = {
# 'random':
# masked.shuffled_mask,
# 'per_neuron':
# masked.shuffled_neuron_mask,
# 'per_neuron_no_input_ablation':
# masked.shuffled_neuron_no_input_ablation_mask,
# 'symmetric':
# masked.symmetric_mask,
# }
# def create_mask(mask_type, base_model,
# rng, sparsity,
# **kwargs):
#
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
. Output only the next line. | return mask_factory.create_mask( |
Continue the code snippet: <|code_start|># Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for weight_symmetry.models.model_factory."""
class MaskedDense(flax.deprecated.nn.Module):
"""Single-layer Dense Masked Network."""
NUM_FEATURES: int = 32
def apply(self,
inputs,
mask = None):
inputs = inputs.reshape(inputs.shape[0], -1)
<|code_end|>
. Use current file imports:
from typing import Mapping, Optional
from absl.testing import absltest
from absl.testing import parameterized
from rigl.experimental.jax.pruning import mask_factory
from rigl.experimental.jax.pruning import masked
import flax
import jax
import jax.numpy as jnp
and context (classes, functions, or code) from other files:
# Path: rigl/experimental/jax/pruning/mask_factory.py
# MASK_TYPES: Mapping[str, MaskFnType] = {
# 'random':
# masked.shuffled_mask,
# 'per_neuron':
# masked.shuffled_neuron_mask,
# 'per_neuron_no_input_ablation':
# masked.shuffled_neuron_no_input_ablation_mask,
# 'symmetric':
# masked.symmetric_mask,
# }
# def create_mask(mask_type, base_model,
# rng, sparsity,
# **kwargs):
#
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
. Output only the next line. | return masked.MaskedModule( |
Based on the snippet: <|code_start|> masked_layer_indices: The layer indices of layers in model to be masked.
Returns:
A tensor of shape (batch, num_classes), containing the logit output.
Raises:
ValueError if the number of pooling layers is too many for the given input
size.
"""
# Note: First dim is batch, last dim is channels, other dims are "spatial".
if not all([(dim >= 2**len(filters)) for dim in inputs.shape[1:-2]]):
raise ValueError(
'Input spatial size, {}, does not allow {} pooling layers.'.format(
str(inputs.shape[1:-2]), len(filters))
)
depth = 2 + len(filters)
masks = masked.generate_model_masks(depth, masks,
masked_layer_indices)
batch_norm = flax.deprecated.nn.BatchNorm.partial(
use_running_average=not train, momentum=0.99, epsilon=1e-5)
for i, filter_num in enumerate(filters):
if f'MaskedModule_{i}' in masks:
logging.info('Layer %d is masked in model', i)
mask = masks[f'MaskedModule_{i}']
inputs = masked.masked(flax.deprecated.nn.Conv, mask)(
inputs,
features=filter_num,
kernel_size=filter_shape,
<|code_end|>
, predict the immediate next line with the help of imports:
from typing import Callable, Mapping, Optional, Sequence
from absl import logging
from rigl.experimental.jax.pruning import init
from rigl.experimental.jax.pruning import masked
import flax
import jax.numpy as jnp
and context (classes, functions, sometimes code) from other files:
# Path: rigl/experimental/jax/pruning/init.py
# def init(rng, shape, dtype=dtype):
# if mask is None:
# return base_init(rng, shape, dtype)
#
# # Find the ablated neurons in the mask, to determine correct fan_out.
# neuron_weight_count = jnp.sum(
# jnp.reshape(mask, (-1, mask.shape[-1])), axis=0)
# non_zero_neurons = jnp.sum(neuron_weight_count != 0)
#
# # Special case of completely ablated weight matrix/layer.
# if jnp.sum(non_zero_neurons) == 0:
# print('Empty weight mask!')
# return jnp.zeros(shape, dtype)
#
# # Neurons have different fan_in w/mask, build up initialization per-unit.
# init_cols = []
# rng, *split_rngs = jax.random.split(rng, mask.shape[-1] + 1)
# for i in range(mask.shape[-1]):
# # Special case of ablated neuron.
# if neuron_weight_count[i] == 0:
# init_cols.append(jnp.zeros(shape[:-1] + (1,), dtype))
# continue
#
# # Fake shape of weight matrix with correct fan_in, and fan_out.
# sparse_shape = (int(neuron_weight_count[i]), int(non_zero_neurons))
#
# # Use only the first column of init from initializer, since faked fan_out.
# init = base_init(split_rngs[i], sparse_shape, dtype)[Ellipsis, 0]
#
# # Expand out to full sparse array.
# expanded_init = jnp.zeros(
# mask[Ellipsis, i].shape,
# dtype).flatten().at[jnp.where(mask[Ellipsis, i].flatten() == 1)].set(init)
# expanded_init = jnp.reshape(expanded_init, mask[Ellipsis, i].shape)
# init_cols.append(expanded_init[Ellipsis, jnp.newaxis])
#
# return jnp.concatenate(init_cols, axis=-1)
#
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
. Output only the next line. | kernel_init=init.sparse_init( |
Predict the next line after this snippet: <|code_start|>
Args:
inputs: Input data with dimensions (batch, spatial_dims..., features).
num_classes: Number of classes in the dataset.
filter_shape: Shape of the convolutional filters.
filters: Number of filters in each convolutional layer, and number of conv
layers (given by length of sequence).
dense_size: Number of filters in each convolutional layer, and number of
conv layers (given by length of sequence).
train: If model is being evaluated in training mode or not.
init_fn: Initialization function used for convolutional layers.
activation_fn: Activation function to be used for convolutional layers.
masks: Masks of the layers in this model, in the same form as
module params, or None.
masked_layer_indices: The layer indices of layers in model to be masked.
Returns:
A tensor of shape (batch, num_classes), containing the logit output.
Raises:
ValueError if the number of pooling layers is too many for the given input
size.
"""
# Note: First dim is batch, last dim is channels, other dims are "spatial".
if not all([(dim >= 2**len(filters)) for dim in inputs.shape[1:-2]]):
raise ValueError(
'Input spatial size, {}, does not allow {} pooling layers.'.format(
str(inputs.shape[1:-2]), len(filters))
)
depth = 2 + len(filters)
<|code_end|>
using the current file's imports:
from typing import Callable, Mapping, Optional, Sequence
from absl import logging
from rigl.experimental.jax.pruning import init
from rigl.experimental.jax.pruning import masked
import flax
import jax.numpy as jnp
and any relevant context from other files:
# Path: rigl/experimental/jax/pruning/init.py
# def init(rng, shape, dtype=dtype):
# if mask is None:
# return base_init(rng, shape, dtype)
#
# # Find the ablated neurons in the mask, to determine correct fan_out.
# neuron_weight_count = jnp.sum(
# jnp.reshape(mask, (-1, mask.shape[-1])), axis=0)
# non_zero_neurons = jnp.sum(neuron_weight_count != 0)
#
# # Special case of completely ablated weight matrix/layer.
# if jnp.sum(non_zero_neurons) == 0:
# print('Empty weight mask!')
# return jnp.zeros(shape, dtype)
#
# # Neurons have different fan_in w/mask, build up initialization per-unit.
# init_cols = []
# rng, *split_rngs = jax.random.split(rng, mask.shape[-1] + 1)
# for i in range(mask.shape[-1]):
# # Special case of ablated neuron.
# if neuron_weight_count[i] == 0:
# init_cols.append(jnp.zeros(shape[:-1] + (1,), dtype))
# continue
#
# # Fake shape of weight matrix with correct fan_in, and fan_out.
# sparse_shape = (int(neuron_weight_count[i]), int(non_zero_neurons))
#
# # Use only the first column of init from initializer, since faked fan_out.
# init = base_init(split_rngs[i], sparse_shape, dtype)[Ellipsis, 0]
#
# # Expand out to full sparse array.
# expanded_init = jnp.zeros(
# mask[Ellipsis, i].shape,
# dtype).flatten().at[jnp.where(mask[Ellipsis, i].flatten() == 1)].set(init)
# expanded_init = jnp.reshape(expanded_init, mask[Ellipsis, i].shape)
# init_cols.append(expanded_init[Ellipsis, jnp.newaxis])
#
# return jnp.concatenate(init_cols, axis=-1)
#
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
. Output only the next line. | masks = masked.generate_model_masks(depth, masks, |
Based on the snippet: <|code_start|>
prune --xm_runlocal --dataset=MNIST --model=MNIST_FC --epochs=10
--pruning_rate=0.95
Command for training and pruning an MNIST fully-connected model for 10
epochs, with pruning rates 0.3, 0.6 and 0.95 at epochs 2, 5, and 8 respectively
for all layers:
prune --xm_runlocal --dataset=MNIST --model=MNIST_FC --epochs=10
--pruning_schedule='[(2, 0.3), (5, 0.6), (8, 0.95)]'
Command for doing the same, but performing pruning only on the second layer:
prune --xm_runlocal --dataset=MNIST --model=MNIST_FC --epochs=10
--pruning_schedule="{'1': [(2, 0.3), (5, 0.6), (8, 0.95)]}"
"""
experiment_dir = path.join(FLAGS.experiment_dir, str(work_unit_id))
logging.info('Saving experimental results to %s', experiment_dir)
host_count = jax.host_count()
local_device_count = jax.local_device_count()
logging.info('Device count: %d, host count: %d, local device count: %d',
jax.device_count(), host_count, local_device_count)
if jax.host_id() == 0:
summary_writer = tensorboard.SummaryWriter(experiment_dir)
<|code_end|>
, predict the immediate next line with the help of imports:
import ast
import collections
import functools
import uuid
import flax
import jax
import jax.numpy as jnp
from os import path
from typing import List
from absl import app
from absl import flags
from absl import logging
from flax.metrics import tensorboard
from flax.training import lr_schedule
from rigl.experimental.jax.datasets import dataset_factory
from rigl.experimental.jax.models import model_factory
from rigl.experimental.jax.training import training
from rigl.experimental.jax.utils import utils
and context (classes, functions, sometimes code) from other files:
# Path: rigl/experimental/jax/datasets/dataset_factory.py
# DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
# 'MNIST': mnist.MNISTDataset,
# 'CIFAR10': cifar10.CIFAR10Dataset,
# }
# def create_dataset(name, *args, **kwargs):
#
# Path: rigl/experimental/jax/models/model_factory.py
# MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
# 'MNIST_CNN': mnist_cnn.MNISTCNN,
# 'MNIST_FC': mnist_fc.MNISTFC,
# 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
# }
# def create_model(
# name, rng,
# input_specs, **kwargs
# ):
# def update_model(model,
# **kwargs):
#
# Path: rigl/experimental/jax/training/training.py
# LABELKEY = dataset_base.ImageDataset.LABELKEY
# DATAKEY = dataset_base.ImageDataset.DATAKEY
# def _shard_batch(xs):
# def _prepare(x):
# def train_step(
# optimizer: flax.optim.Optimizer, batch: Mapping[str, jnp.array],
# rng: Callable[[int], jnp.array], state: flax.deprecated.nn.Collection,
# learning_rate_fn: Callable[[int], float]
# ) -> Tuple[flax.optim.Optimizer, flax.deprecated.nn.Collection, float, float]:
# def loss_fn(
# model: flax.deprecated.nn.Model
# ) -> Tuple[float, Tuple[flax.deprecated.nn.Collection, jnp.array]]:
# def __init__(
# self,
# optimizer_def: flax.optim.OptimizerDef,
# initial_model: flax.deprecated.nn.Model,
# initial_state: flax.deprecated.nn.Collection,
# dataset: jnp.array,
# rng: Callable[[int], jnp.array] = None,
# summary_writer: Optional[tf.summary.SummaryWriter] = None,
# ):
# class Trainer:
#
# Path: rigl/experimental/jax/utils/utils.py
# def cross_entropy_loss(log_softmax_logits,
# labels):
# def compute_metrics(logits,
# labels):
# def _np_converter(obj):
# def dump_dict_json(data_dict, path):
# def count_param(model,
# param_names):
# def cosine_similarity(a, b):
# def param_as_array(params):
# def cosine_similarity_model(initial_model,
# current_model):
# def vector_difference_norm_model(initial_model,
# current_model):
# def pairwise_longest(iterable):
# T = TypeVar('T')
. Output only the next line. | dataset = dataset_factory.create_dataset( |
Using the snippet: <|code_start|>Command for doing the same, but performing pruning only on the second layer:
prune --xm_runlocal --dataset=MNIST --model=MNIST_FC --epochs=10
--pruning_schedule="{'1': [(2, 0.3), (5, 0.6), (8, 0.95)]}"
"""
experiment_dir = path.join(FLAGS.experiment_dir, str(work_unit_id))
logging.info('Saving experimental results to %s', experiment_dir)
host_count = jax.host_count()
local_device_count = jax.local_device_count()
logging.info('Device count: %d, host count: %d, local device count: %d',
jax.device_count(), host_count, local_device_count)
if jax.host_id() == 0:
summary_writer = tensorboard.SummaryWriter(experiment_dir)
dataset = dataset_factory.create_dataset(
FLAGS.dataset,
FLAGS.batch_size,
FLAGS.batch_size_test,
shuffle_buffer_size=FLAGS.shuffle_buffer_size)
logging.info('Training %s on the %s dataset...', FLAGS.model, FLAGS.dataset)
rng = jax.random.PRNGKey(FLAGS.random_seed)
input_shape = (1,) + dataset.shape
<|code_end|>
, determine the next line of code. You have imports:
import ast
import collections
import functools
import uuid
import flax
import jax
import jax.numpy as jnp
from os import path
from typing import List
from absl import app
from absl import flags
from absl import logging
from flax.metrics import tensorboard
from flax.training import lr_schedule
from rigl.experimental.jax.datasets import dataset_factory
from rigl.experimental.jax.models import model_factory
from rigl.experimental.jax.training import training
from rigl.experimental.jax.utils import utils
and context (class names, function names, or code) available:
# Path: rigl/experimental/jax/datasets/dataset_factory.py
# DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
# 'MNIST': mnist.MNISTDataset,
# 'CIFAR10': cifar10.CIFAR10Dataset,
# }
# def create_dataset(name, *args, **kwargs):
#
# Path: rigl/experimental/jax/models/model_factory.py
# MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
# 'MNIST_CNN': mnist_cnn.MNISTCNN,
# 'MNIST_FC': mnist_fc.MNISTFC,
# 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
# }
# def create_model(
# name, rng,
# input_specs, **kwargs
# ):
# def update_model(model,
# **kwargs):
#
# Path: rigl/experimental/jax/training/training.py
# LABELKEY = dataset_base.ImageDataset.LABELKEY
# DATAKEY = dataset_base.ImageDataset.DATAKEY
# def _shard_batch(xs):
# def _prepare(x):
# def train_step(
# optimizer: flax.optim.Optimizer, batch: Mapping[str, jnp.array],
# rng: Callable[[int], jnp.array], state: flax.deprecated.nn.Collection,
# learning_rate_fn: Callable[[int], float]
# ) -> Tuple[flax.optim.Optimizer, flax.deprecated.nn.Collection, float, float]:
# def loss_fn(
# model: flax.deprecated.nn.Model
# ) -> Tuple[float, Tuple[flax.deprecated.nn.Collection, jnp.array]]:
# def __init__(
# self,
# optimizer_def: flax.optim.OptimizerDef,
# initial_model: flax.deprecated.nn.Model,
# initial_state: flax.deprecated.nn.Collection,
# dataset: jnp.array,
# rng: Callable[[int], jnp.array] = None,
# summary_writer: Optional[tf.summary.SummaryWriter] = None,
# ):
# class Trainer:
#
# Path: rigl/experimental/jax/utils/utils.py
# def cross_entropy_loss(log_softmax_logits,
# labels):
# def compute_metrics(logits,
# labels):
# def _np_converter(obj):
# def dump_dict_json(data_dict, path):
# def count_param(model,
# param_names):
# def cosine_similarity(a, b):
# def param_as_array(params):
# def cosine_similarity_model(initial_model,
# current_model):
# def vector_difference_norm_model(initial_model,
# current_model):
# def pairwise_longest(iterable):
# T = TypeVar('T')
. Output only the next line. | base_model, _ = model_factory.create_model( |
Here is a snippet: <|code_start|> lr_fn = lr_schedule.create_constant_learning_rate_schedule(
FLAGS.lr, steps_per_epoch)
elif FLAGS.lr_schedule == LR_SCHEDULE_STEPPED:
lr_schedule_steps = ast.literal_eval(FLAGS.lr_schedule_steps)
lr_fn = lr_schedule.create_stepped_learning_rate_schedule(
FLAGS.lr, steps_per_epoch, lr_schedule_steps)
elif FLAGS.lr_schedule == LR_SCHEDULE_COSINE:
lr_fn = lr_schedule.create_cosine_learning_rate_schedule(
FLAGS.lr, steps_per_epoch, FLAGS.epochs)
else:
raise ValueError(f'Unknown LR schedule type {FLAGS.lr_schedule}')
# Reuses the FLAX learning rate schedule framework for pruning rate schedule.
pruning_fn_p = functools.partial(
lr_schedule.create_stepped_learning_rate_schedule, FLAGS.pruning_rate,
steps_per_epoch)
if FLAGS.pruning_schedule:
pruning_schedule = ast.literal_eval(FLAGS.pruning_schedule)
if isinstance(pruning_schedule, collections.Mapping):
pruning_rate_fn = {
f'MaskedModule_{layer_num}': pruning_fn_p(schedule)
for layer_num, schedule in pruning_schedule.items()
}
else:
pruning_rate_fn = pruning_fn_p(pruning_schedule)
else:
pruning_rate_fn = lr_schedule.create_constant_learning_rate_schedule(
FLAGS.pruning_rate, steps_per_epoch)
if jax.host_id() == 0:
<|code_end|>
. Write the next line using the current file imports:
import ast
import collections
import functools
import uuid
import flax
import jax
import jax.numpy as jnp
from os import path
from typing import List
from absl import app
from absl import flags
from absl import logging
from flax.metrics import tensorboard
from flax.training import lr_schedule
from rigl.experimental.jax.datasets import dataset_factory
from rigl.experimental.jax.models import model_factory
from rigl.experimental.jax.training import training
from rigl.experimental.jax.utils import utils
and context from other files:
# Path: rigl/experimental/jax/datasets/dataset_factory.py
# DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
# 'MNIST': mnist.MNISTDataset,
# 'CIFAR10': cifar10.CIFAR10Dataset,
# }
# def create_dataset(name, *args, **kwargs):
#
# Path: rigl/experimental/jax/models/model_factory.py
# MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
# 'MNIST_CNN': mnist_cnn.MNISTCNN,
# 'MNIST_FC': mnist_fc.MNISTFC,
# 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
# }
# def create_model(
# name, rng,
# input_specs, **kwargs
# ):
# def update_model(model,
# **kwargs):
#
# Path: rigl/experimental/jax/training/training.py
# LABELKEY = dataset_base.ImageDataset.LABELKEY
# DATAKEY = dataset_base.ImageDataset.DATAKEY
# def _shard_batch(xs):
# def _prepare(x):
# def train_step(
# optimizer: flax.optim.Optimizer, batch: Mapping[str, jnp.array],
# rng: Callable[[int], jnp.array], state: flax.deprecated.nn.Collection,
# learning_rate_fn: Callable[[int], float]
# ) -> Tuple[flax.optim.Optimizer, flax.deprecated.nn.Collection, float, float]:
# def loss_fn(
# model: flax.deprecated.nn.Model
# ) -> Tuple[float, Tuple[flax.deprecated.nn.Collection, jnp.array]]:
# def __init__(
# self,
# optimizer_def: flax.optim.OptimizerDef,
# initial_model: flax.deprecated.nn.Model,
# initial_state: flax.deprecated.nn.Collection,
# dataset: jnp.array,
# rng: Callable[[int], jnp.array] = None,
# summary_writer: Optional[tf.summary.SummaryWriter] = None,
# ):
# class Trainer:
#
# Path: rigl/experimental/jax/utils/utils.py
# def cross_entropy_loss(log_softmax_logits,
# labels):
# def compute_metrics(logits,
# labels):
# def _np_converter(obj):
# def dump_dict_json(data_dict, path):
# def count_param(model,
# param_names):
# def cosine_similarity(a, b):
# def param_as_array(params):
# def cosine_similarity_model(initial_model,
# current_model):
# def vector_difference_norm_model(initial_model,
# current_model):
# def pairwise_longest(iterable):
# T = TypeVar('T')
, which may include functions, classes, or code. Output only the next line. | trainer = training.Trainer( |
Based on the snippet: <|code_start|> pruning_rate_fn = pruning_fn_p(pruning_schedule)
else:
pruning_rate_fn = lr_schedule.create_constant_learning_rate_schedule(
FLAGS.pruning_rate, steps_per_epoch)
if jax.host_id() == 0:
trainer = training.Trainer(
optimizer,
initial_model,
initial_state,
dataset,
rng,
summary_writer=summary_writer,
)
else:
trainer = training.Trainer(
optimizer, initial_model, initial_state, dataset, rng)
_, best_metrics = trainer.train(
FLAGS.epochs,
lr_fn=lr_fn,
pruning_rate_fn=pruning_rate_fn,
update_iter=FLAGS.update_iterations,
update_epoch=FLAGS.update_epoch,
)
logging.info('Best metrics: %s', str(best_metrics))
if jax.host_id() == 0:
if FLAGS.dump_json:
<|code_end|>
, predict the immediate next line with the help of imports:
import ast
import collections
import functools
import uuid
import flax
import jax
import jax.numpy as jnp
from os import path
from typing import List
from absl import app
from absl import flags
from absl import logging
from flax.metrics import tensorboard
from flax.training import lr_schedule
from rigl.experimental.jax.datasets import dataset_factory
from rigl.experimental.jax.models import model_factory
from rigl.experimental.jax.training import training
from rigl.experimental.jax.utils import utils
and context (classes, functions, sometimes code) from other files:
# Path: rigl/experimental/jax/datasets/dataset_factory.py
# DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
# 'MNIST': mnist.MNISTDataset,
# 'CIFAR10': cifar10.CIFAR10Dataset,
# }
# def create_dataset(name, *args, **kwargs):
#
# Path: rigl/experimental/jax/models/model_factory.py
# MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
# 'MNIST_CNN': mnist_cnn.MNISTCNN,
# 'MNIST_FC': mnist_fc.MNISTFC,
# 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
# }
# def create_model(
# name, rng,
# input_specs, **kwargs
# ):
# def update_model(model,
# **kwargs):
#
# Path: rigl/experimental/jax/training/training.py
# LABELKEY = dataset_base.ImageDataset.LABELKEY
# DATAKEY = dataset_base.ImageDataset.DATAKEY
# def _shard_batch(xs):
# def _prepare(x):
# def train_step(
# optimizer: flax.optim.Optimizer, batch: Mapping[str, jnp.array],
# rng: Callable[[int], jnp.array], state: flax.deprecated.nn.Collection,
# learning_rate_fn: Callable[[int], float]
# ) -> Tuple[flax.optim.Optimizer, flax.deprecated.nn.Collection, float, float]:
# def loss_fn(
# model: flax.deprecated.nn.Model
# ) -> Tuple[float, Tuple[flax.deprecated.nn.Collection, jnp.array]]:
# def __init__(
# self,
# optimizer_def: flax.optim.OptimizerDef,
# initial_model: flax.deprecated.nn.Model,
# initial_state: flax.deprecated.nn.Collection,
# dataset: jnp.array,
# rng: Callable[[int], jnp.array] = None,
# summary_writer: Optional[tf.summary.SummaryWriter] = None,
# ):
# class Trainer:
#
# Path: rigl/experimental/jax/utils/utils.py
# def cross_entropy_loss(log_softmax_logits,
# labels):
# def compute_metrics(logits,
# labels):
# def _np_converter(obj):
# def dump_dict_json(data_dict, path):
# def count_param(model,
# param_names):
# def cosine_similarity(a, b):
# def param_as_array(params):
# def cosine_similarity_model(initial_model,
# current_model):
# def vector_difference_norm_model(initial_model,
# current_model):
# def pairwise_longest(iterable):
# T = TypeVar('T')
. Output only the next line. | utils.dump_dict_json(best_metrics, |
Here is a snippet: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for weight_symmetry.pruning.symmetry."""
class MaskedDense(flax.deprecated.nn.Module):
"""Single-layer Dense Masked Network.
Attributes:
NUM_FEATURES: The number of neurons in the single dense layer.
"""
NUM_FEATURES: int = 16
def apply(self,
inputs,
mask = None):
inputs = inputs.reshape(inputs.shape[0], -1)
<|code_end|>
. Write the next line using the current file imports:
import functools
import math
import operator
import flax
import jax
import jax.numpy as jnp
import numpy as np
from typing import Mapping, Optional, Sequence
from absl.testing import absltest
from absl.testing import parameterized
from rigl.experimental.jax.pruning import masked
from rigl.experimental.jax.pruning import symmetry
and context from other files:
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
#
# Path: rigl/experimental/jax/pruning/symmetry.py
# def count_permutations_mask_layer(
# mask_layer,
# next_mask_layer = None,
# parameter_key = 'kernel'):
# def count_permutations_mask(mask):
# def get_mask_stats(mask):
, which may include functions, classes, or code. Output only the next line. | return masked.MaskedModule( |
Given the following code snippet before the placeholder: <|code_start|>
def setUp(self):
super().setUp()
self._rng = jax.random.PRNGKey(42)
self._batch_size = 2
self._input_shape = ((self._batch_size, 2, 2, 1), jnp.float32)
self._flat_input_shape = ((self._batch_size, 2 * 2 * 1), jnp.float32)
_, initial_params = MaskedDense.init_by_shape(self._rng,
(self._flat_input_shape,))
self._masked_model = flax.deprecated.nn.Model(MaskedDense, initial_params)
_, initial_params = MaskedConv.init_by_shape(self._rng,
(self._input_shape,))
self._masked_conv_model = flax.deprecated.nn.Model(MaskedConv,
initial_params)
_, initial_params = MaskedTwoLayerDense.init_by_shape(
self._rng, (self._flat_input_shape,))
self._masked_two_layer_model = flax.deprecated.nn.Model(
MaskedTwoLayerDense, initial_params)
def test_count_permutations_layer_mask_full(self):
"""Tests count of weight permutations in a full mask."""
mask_layer = {
'kernel':
jnp.ones(self._masked_model.params['MaskedModule_0']['unmasked']
['kernel'].shape),
}
<|code_end|>
, predict the next line using imports from the current file:
import functools
import math
import operator
import flax
import jax
import jax.numpy as jnp
import numpy as np
from typing import Mapping, Optional, Sequence
from absl.testing import absltest
from absl.testing import parameterized
from rigl.experimental.jax.pruning import masked
from rigl.experimental.jax.pruning import symmetry
and context including class names, function names, and sometimes code from other files:
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
#
# Path: rigl/experimental/jax/pruning/symmetry.py
# def count_permutations_mask_layer(
# mask_layer,
# next_mask_layer = None,
# parameter_key = 'kernel'):
# def count_permutations_mask(mask):
# def get_mask_stats(mask):
. Output only the next line. | stats = symmetry.count_permutations_mask_layer(mask_layer) |
Continue the code snippet: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Dataset Factory.
Dataset factory to allow us to easily use tensorflow datasets (TFDS)
with JAX/FLAX, by defining a bunch of wrappers, including preprocessing.
Attributes:
DATASETS: A list of the datasets that can be created.
"""
DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
'MNIST': mnist.MNISTDataset,
<|code_end|>
. Use current file imports:
from typing import Any, Mapping, Type
from rigl.experimental.jax.datasets import cifar10
from rigl.experimental.jax.datasets import dataset_base
from rigl.experimental.jax.datasets import mnist
import tensorflow.compat.v2 as tf
and context (classes, functions, or code) from other files:
# Path: rigl/experimental/jax/datasets/cifar10.py
# class CIFAR10Dataset(dataset_base.ImageDataset):
# NAME: str = 'cifar10'
# MEAN_RGB: Sequence[float] = [0.4914 * 255, 0.4822 * 255, 0.4465 * 255]
# STDDEV_RGB: Sequence[float] = [0.2470 * 255, 0.2435 * 255, 0.2616 * 255]
# def __init__(self,
# batch_size,
# batch_size_test,
# shuffle_buffer_size = 1024,
# seed = 42):
# def preprocess(
# self, data):
#
# Path: rigl/experimental/jax/datasets/dataset_base.py
# class Dataset(metaclass=abc.ABCMeta):
# class ImageDataset(Dataset):
# DATAKEY: Optional[str] = None
# LABELKEY: str = 'label'
# DATAKEY = 'image'
# def __init__(self,
# name,
# batch_size,
# batch_size_test,
# shuffle_buffer_size,
# prefetch_size = 1,
# seed = None): # pytype: disable=annotation-type-mismatch
# def _dataset_dir(self):
# def get_train(self):
# def get_train_len(self):
# def get_test(self):
# def get_test_len(self):
# def preprocess(
# self, data):
# def augment(
# self, data):
# def preprocess(
# self, data):
#
# Path: rigl/experimental/jax/datasets/mnist.py
# class MNISTDataset(dataset_base.ImageDataset):
# NAME: str = 'mnist'
# def __init__(self,
# batch_size,
# batch_size_test,
# shuffle_buffer_size = 1024,
# seed = 42):
# def preprocess(
# self, data):
. Output only the next line. | 'CIFAR10': cifar10.CIFAR10Dataset, |
Predict the next line after this snippet: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Dataset Factory.
Dataset factory to allow us to easily use tensorflow datasets (TFDS)
with JAX/FLAX, by defining a bunch of wrappers, including preprocessing.
Attributes:
DATASETS: A list of the datasets that can be created.
"""
<|code_end|>
using the current file's imports:
from typing import Any, Mapping, Type
from rigl.experimental.jax.datasets import cifar10
from rigl.experimental.jax.datasets import dataset_base
from rigl.experimental.jax.datasets import mnist
import tensorflow.compat.v2 as tf
and any relevant context from other files:
# Path: rigl/experimental/jax/datasets/cifar10.py
# class CIFAR10Dataset(dataset_base.ImageDataset):
# NAME: str = 'cifar10'
# MEAN_RGB: Sequence[float] = [0.4914 * 255, 0.4822 * 255, 0.4465 * 255]
# STDDEV_RGB: Sequence[float] = [0.2470 * 255, 0.2435 * 255, 0.2616 * 255]
# def __init__(self,
# batch_size,
# batch_size_test,
# shuffle_buffer_size = 1024,
# seed = 42):
# def preprocess(
# self, data):
#
# Path: rigl/experimental/jax/datasets/dataset_base.py
# class Dataset(metaclass=abc.ABCMeta):
# class ImageDataset(Dataset):
# DATAKEY: Optional[str] = None
# LABELKEY: str = 'label'
# DATAKEY = 'image'
# def __init__(self,
# name,
# batch_size,
# batch_size_test,
# shuffle_buffer_size,
# prefetch_size = 1,
# seed = None): # pytype: disable=annotation-type-mismatch
# def _dataset_dir(self):
# def get_train(self):
# def get_train_len(self):
# def get_test(self):
# def get_test_len(self):
# def preprocess(
# self, data):
# def augment(
# self, data):
# def preprocess(
# self, data):
#
# Path: rigl/experimental/jax/datasets/mnist.py
# class MNISTDataset(dataset_base.ImageDataset):
# NAME: str = 'mnist'
# def __init__(self,
# batch_size,
# batch_size_test,
# shuffle_buffer_size = 1024,
# seed = 42):
# def preprocess(
# self, data):
. Output only the next line. | DATASETS: Mapping[str, Type[dataset_base.Dataset]] = { |
Continue the code snippet: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Dataset Factory.
Dataset factory to allow us to easily use tensorflow datasets (TFDS)
with JAX/FLAX, by defining a bunch of wrappers, including preprocessing.
Attributes:
DATASETS: A list of the datasets that can be created.
"""
DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
<|code_end|>
. Use current file imports:
from typing import Any, Mapping, Type
from rigl.experimental.jax.datasets import cifar10
from rigl.experimental.jax.datasets import dataset_base
from rigl.experimental.jax.datasets import mnist
import tensorflow.compat.v2 as tf
and context (classes, functions, or code) from other files:
# Path: rigl/experimental/jax/datasets/cifar10.py
# class CIFAR10Dataset(dataset_base.ImageDataset):
# NAME: str = 'cifar10'
# MEAN_RGB: Sequence[float] = [0.4914 * 255, 0.4822 * 255, 0.4465 * 255]
# STDDEV_RGB: Sequence[float] = [0.2470 * 255, 0.2435 * 255, 0.2616 * 255]
# def __init__(self,
# batch_size,
# batch_size_test,
# shuffle_buffer_size = 1024,
# seed = 42):
# def preprocess(
# self, data):
#
# Path: rigl/experimental/jax/datasets/dataset_base.py
# class Dataset(metaclass=abc.ABCMeta):
# class ImageDataset(Dataset):
# DATAKEY: Optional[str] = None
# LABELKEY: str = 'label'
# DATAKEY = 'image'
# def __init__(self,
# name,
# batch_size,
# batch_size_test,
# shuffle_buffer_size,
# prefetch_size = 1,
# seed = None): # pytype: disable=annotation-type-mismatch
# def _dataset_dir(self):
# def get_train(self):
# def get_train_len(self):
# def get_test(self):
# def get_test_len(self):
# def preprocess(
# self, data):
# def augment(
# self, data):
# def preprocess(
# self, data):
#
# Path: rigl/experimental/jax/datasets/mnist.py
# class MNISTDataset(dataset_base.ImageDataset):
# NAME: str = 'mnist'
# def __init__(self,
# batch_size,
# batch_size_test,
# shuffle_buffer_size = 1024,
# seed = 42):
# def preprocess(
# self, data):
. Output only the next line. | 'MNIST': mnist.MNISTDataset, |
Next line prediction: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for weight_symmetry.datasets.dataset_common."""
class DatasetCommonTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self._batch_size = 32
self._batch_size_test = 10
self._shuffle_buffer_size = 128
def _create_dataset(self, dataset_name):
"""Helper function for creating a dataset."""
return dataset_factory.create_dataset(
dataset_name,
self._batch_size,
self._batch_size_test,
shuffle_buffer_size=self._shuffle_buffer_size)
def test_dataset_supported(self):
"""Tests supported datasets."""
for dataset_name in dataset_factory.DATASETS:
dataset = self._create_dataset(dataset_name)
<|code_end|>
. Use current file imports:
(from absl.testing import absltest
from absl.testing import parameterized
from rigl.experimental.jax.datasets import dataset_base
from rigl.experimental.jax.datasets import dataset_factory
import numpy as np)
and context including class names, function names, or small code snippets from other files:
# Path: rigl/experimental/jax/datasets/dataset_base.py
# class Dataset(metaclass=abc.ABCMeta):
# class ImageDataset(Dataset):
# DATAKEY: Optional[str] = None
# LABELKEY: str = 'label'
# DATAKEY = 'image'
# def __init__(self,
# name,
# batch_size,
# batch_size_test,
# shuffle_buffer_size,
# prefetch_size = 1,
# seed = None): # pytype: disable=annotation-type-mismatch
# def _dataset_dir(self):
# def get_train(self):
# def get_train_len(self):
# def get_test(self):
# def get_test_len(self):
# def preprocess(
# self, data):
# def augment(
# self, data):
# def preprocess(
# self, data):
#
# Path: rigl/experimental/jax/datasets/dataset_factory.py
# DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
# 'MNIST': mnist.MNISTDataset,
# 'CIFAR10': cifar10.CIFAR10Dataset,
# }
# def create_dataset(name, *args, **kwargs):
. Output only the next line. | self.assertIsInstance(dataset, dataset_base.Dataset) |
Based on the snippet: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for weight_symmetry.datasets.dataset_common."""
class DatasetCommonTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self._batch_size = 32
self._batch_size_test = 10
self._shuffle_buffer_size = 128
def _create_dataset(self, dataset_name):
"""Helper function for creating a dataset."""
<|code_end|>
, predict the immediate next line with the help of imports:
from absl.testing import absltest
from absl.testing import parameterized
from rigl.experimental.jax.datasets import dataset_base
from rigl.experimental.jax.datasets import dataset_factory
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: rigl/experimental/jax/datasets/dataset_base.py
# class Dataset(metaclass=abc.ABCMeta):
# class ImageDataset(Dataset):
# DATAKEY: Optional[str] = None
# LABELKEY: str = 'label'
# DATAKEY = 'image'
# def __init__(self,
# name,
# batch_size,
# batch_size_test,
# shuffle_buffer_size,
# prefetch_size = 1,
# seed = None): # pytype: disable=annotation-type-mismatch
# def _dataset_dir(self):
# def get_train(self):
# def get_train_len(self):
# def get_test(self):
# def get_test_len(self):
# def preprocess(
# self, data):
# def augment(
# self, data):
# def preprocess(
# self, data):
#
# Path: rigl/experimental/jax/datasets/dataset_factory.py
# DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
# 'MNIST': mnist.MNISTDataset,
# 'CIFAR10': cifar10.CIFAR10Dataset,
# }
# def create_dataset(name, *args, **kwargs):
. Output only the next line. | return dataset_factory.create_dataset( |
Using the snippet: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for weight_symmetry.models.model_factory."""
class ModelCommonTest(parameterized.TestCase):
"""Tests the model factory."""
def setUp(self):
super().setUp()
self._rng = jax.random.PRNGKey(42)
self._input_shape = ((1, 28, 28, 1), jnp.float32)
self._num_classes = 10
def _create_model(self, model_name):
<|code_end|>
, determine the next line of code. You have imports:
from absl.testing import absltest
from absl.testing import parameterized
from rigl.experimental.jax.models import model_factory
import flax
import jax
import jax.numpy as jnp
and context (class names, function names, or code) available:
# Path: rigl/experimental/jax/models/model_factory.py
# MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
# 'MNIST_CNN': mnist_cnn.MNISTCNN,
# 'MNIST_FC': mnist_fc.MNISTFC,
# 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
# }
# def create_model(
# name, rng,
# input_specs, **kwargs
# ):
# def update_model(model,
# **kwargs):
. Output only the next line. | return model_factory.create_model( |
Predict the next line after this snippet: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Factory for neural network models.
Attributes:
MODELS: A list of the models that can be created.
"""
MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
'MNIST_CNN': mnist_cnn.MNISTCNN,
'MNIST_FC': mnist_fc.MNISTFC,
<|code_end|>
using the current file's imports:
from typing import Any, Callable, Mapping, Sequence, Tuple, Type
from rigl.experimental.jax.models import cifar10_cnn
from rigl.experimental.jax.models import mnist_cnn
from rigl.experimental.jax.models import mnist_fc
import flax
import jax.numpy as jnp
and any relevant context from other files:
# Path: rigl/experimental/jax/models/cifar10_cnn.py
# class CIFAR10CNN(flax.deprecated.nn.Module):
# def apply(self,
# inputs,
# num_classes,
# filter_shape = (3, 3),
# filters = (32, 32, 64, 64, 128, 128),
# init_fn=flax.deprecated.nn.initializers.kaiming_normal,
# train=True,
# activation_fn = flax.deprecated.nn.relu,
# masks = None,
# masked_layer_indices = None):
#
# Path: rigl/experimental/jax/models/mnist_cnn.py
# class MNISTCNN(flax.deprecated.nn.Module):
# def apply(self,
# inputs,
# num_classes,
# filter_shape = (5, 5),
# filters = (16, 32),
# dense_size = 64,
# train=True,
# init_fn = flax.deprecated.nn.initializers.kaiming_normal,
# activation_fn = flax.deprecated.nn.relu,
# masks = None,
# masked_layer_indices = None):
#
# Path: rigl/experimental/jax/models/mnist_fc.py
# def feature_dim_for_param(input_len,
# param_count,
# depth,
# depth_mult = 2.):
# def apply(self,
# inputs,
# num_classes,
# features = (32, 32),
# train=True,
# init_fn = flax.deprecated.nn.initializers.kaiming_normal,
# activation_fn = flax.deprecated.nn.relu,
# masks = None,
# masked_layer_indices = None,
# dropout_rate = 0.):
# class MNISTFC(flax.deprecated.nn.Module):
. Output only the next line. | 'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN, |
Predict the next line for this snippet: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Factory for neural network models.
Attributes:
MODELS: A list of the models that can be created.
"""
MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
<|code_end|>
with the help of current file imports:
from typing import Any, Callable, Mapping, Sequence, Tuple, Type
from rigl.experimental.jax.models import cifar10_cnn
from rigl.experimental.jax.models import mnist_cnn
from rigl.experimental.jax.models import mnist_fc
import flax
import jax.numpy as jnp
and context from other files:
# Path: rigl/experimental/jax/models/cifar10_cnn.py
# class CIFAR10CNN(flax.deprecated.nn.Module):
# def apply(self,
# inputs,
# num_classes,
# filter_shape = (3, 3),
# filters = (32, 32, 64, 64, 128, 128),
# init_fn=flax.deprecated.nn.initializers.kaiming_normal,
# train=True,
# activation_fn = flax.deprecated.nn.relu,
# masks = None,
# masked_layer_indices = None):
#
# Path: rigl/experimental/jax/models/mnist_cnn.py
# class MNISTCNN(flax.deprecated.nn.Module):
# def apply(self,
# inputs,
# num_classes,
# filter_shape = (5, 5),
# filters = (16, 32),
# dense_size = 64,
# train=True,
# init_fn = flax.deprecated.nn.initializers.kaiming_normal,
# activation_fn = flax.deprecated.nn.relu,
# masks = None,
# masked_layer_indices = None):
#
# Path: rigl/experimental/jax/models/mnist_fc.py
# def feature_dim_for_param(input_len,
# param_count,
# depth,
# depth_mult = 2.):
# def apply(self,
# inputs,
# num_classes,
# features = (32, 32),
# train=True,
# init_fn = flax.deprecated.nn.initializers.kaiming_normal,
# activation_fn = flax.deprecated.nn.relu,
# masks = None,
# masked_layer_indices = None,
# dropout_rate = 0.):
# class MNISTFC(flax.deprecated.nn.Module):
, which may contain function names, class names, or code. Output only the next line. | 'MNIST_CNN': mnist_cnn.MNISTCNN, |
Predict the next line after this snippet: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Factory for neural network models.
Attributes:
MODELS: A list of the models that can be created.
"""
MODELS: Mapping[str, Type[flax.deprecated.nn.Model]] = {
'MNIST_CNN': mnist_cnn.MNISTCNN,
<|code_end|>
using the current file's imports:
from typing import Any, Callable, Mapping, Sequence, Tuple, Type
from rigl.experimental.jax.models import cifar10_cnn
from rigl.experimental.jax.models import mnist_cnn
from rigl.experimental.jax.models import mnist_fc
import flax
import jax.numpy as jnp
and any relevant context from other files:
# Path: rigl/experimental/jax/models/cifar10_cnn.py
# class CIFAR10CNN(flax.deprecated.nn.Module):
# def apply(self,
# inputs,
# num_classes,
# filter_shape = (3, 3),
# filters = (32, 32, 64, 64, 128, 128),
# init_fn=flax.deprecated.nn.initializers.kaiming_normal,
# train=True,
# activation_fn = flax.deprecated.nn.relu,
# masks = None,
# masked_layer_indices = None):
#
# Path: rigl/experimental/jax/models/mnist_cnn.py
# class MNISTCNN(flax.deprecated.nn.Module):
# def apply(self,
# inputs,
# num_classes,
# filter_shape = (5, 5),
# filters = (16, 32),
# dense_size = 64,
# train=True,
# init_fn = flax.deprecated.nn.initializers.kaiming_normal,
# activation_fn = flax.deprecated.nn.relu,
# masks = None,
# masked_layer_indices = None):
#
# Path: rigl/experimental/jax/models/mnist_fc.py
# def feature_dim_for_param(input_len,
# param_count,
# depth,
# depth_mult = 2.):
# def apply(self,
# inputs,
# num_classes,
# features = (32, 32),
# train=True,
# init_fn = flax.deprecated.nn.initializers.kaiming_normal,
# activation_fn = flax.deprecated.nn.relu,
# masks = None,
# masked_layer_indices = None,
# dropout_rate = 0.):
# class MNISTFC(flax.deprecated.nn.Module):
. Output only the next line. | 'MNIST_FC': mnist_fc.MNISTFC, |
Here is a snippet: <|code_start|># coding=utf-8
# Copyright 2022 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for weight_symmetry.datasets.mnist."""
class MNISTDatasetTest(absltest.TestCase):
"""Test cases for MNIST Dataset."""
def setUp(self):
"""Common setup routines/variables for test cases."""
super().setUp()
self._batch_size = 16
self._batch_size_test = 10
self._shuffle_buffer_size = 8
<|code_end|>
. Write the next line using the current file imports:
from absl.testing import absltest
from rigl.experimental.jax.datasets import mnist
import numpy as np
and context from other files:
# Path: rigl/experimental/jax/datasets/mnist.py
# class MNISTDataset(dataset_base.ImageDataset):
# NAME: str = 'mnist'
# def __init__(self,
# batch_size,
# batch_size_test,
# shuffle_buffer_size = 1024,
# seed = 42):
# def preprocess(
# self, data):
, which may include functions, classes, or code. Output only the next line. | self._dataset = mnist.MNISTDataset( |
Predict the next line after this snippet: <|code_start|> 'interpolate',
denylist=['model_start', 'model_end', 'model_inter', 'd_set'])
def interpolate(model_start, model_end, model_inter, d_set,
i_start=-0.2, i_end=1.2, n_interpolation=29):
"""Interpolates between 2 sparse networks linearly and evaluates."""
interpolation_coefs = np.linspace(i_start, i_end, n_interpolation)
all_scores = {}
for i_coef in interpolation_coefs:
logging.info('Interpolating with: %f', i_coef)
for var_start, var_end, var_inter in zip(model_start.trainable_variables,
model_end.trainable_variables,
model_inter.trainable_variables):
new_value = (1 - i_coef) * var_start + i_coef * var_end
var_inter.assign(new_value)
scores = test_model(model_inter, d_set)
all_scores[i_coef] = scores
return all_scores
def main(unused_argv):
init_timer = timer.Timer()
init_timer.Start()
if FLAGS.preload_gin_config:
# Load default values from the original experiment, always the first one.
with gin.unlock_config():
gin.parse_config_file(FLAGS.preload_gin_config, skip_unknown=True)
logging.info('Operative Gin configurations loaded from: %s',
FLAGS.preload_gin_config)
gin.parse_config_files_and_bindings(FLAGS.gin_config, FLAGS.gin_bindings)
<|code_end|>
using the current file's imports:
import os
import gin
import numpy as np
import tensorflow.compat.v2 as tf
from absl import app
from absl import flags
from absl import logging
from rigl.rigl_tf2 import utils
from pyglib import timer
and any relevant context from other files:
# Path: rigl/rigl_tf2/utils.py
# FLAGS = flags.FLAGS
# PRUNING_WRAPPER = pruning_wrapper.PruneLowMagnitude
# PRUNED_LAYER_TYPES = (tf.keras.layers.Conv2D, tf.keras.layers.Dense)
# def get_dataset():
# def get_pruning_params(mode='prune',
# initial_sparsity=0.0,
# final_sparsity=0.8,
# begin_step=2000,
# end_step=4000,
# frequency=200):
# def maybe_prune_layer(layer, params, filter_fn):
# def get_network(
# pruning_params,
# input_shape,
# num_classes,
# activation = 'relu',
# network_name = 'lenet5',
# mask_init_path = None,
# shuffle_mask = False,
# weight_init_path = None,
# weight_init_method = None,
# weight_decay = 0.,
# noise_stddev = 0.,
# pruned_layer_types = PRUNED_LAYER_TYPES):
# def get_optimizer(total_steps,
# name = 'adam',
# learning_rate = 0.001,
# clipnorm = None,
# clipvalue = None,
# momentum = None):
. Output only the next line. | data_train, data_test, info = utils.get_dataset() |
Using the snippet: <|code_start|> mask = None):
inputs = inputs.reshape(inputs.shape[0], -1)
layer_mask = mask['MaskedModule_0'] if mask else None
return masked.MaskedModule(
inputs,
features=self.NUM_FEATURES,
wrapped_module=flax.deprecated.nn.Dense,
mask=layer_mask,
kernel_init=flax.deprecated.nn.initializers.kaiming_normal())
class MaskedDenseSparseInit(flax.deprecated.nn.Module):
"""Single-layer Dense Masked Network."""
NUM_FEATURES: int = 32
def apply(self,
inputs,
*args,
mask = None,
**kwargs):
inputs = inputs.reshape(inputs.shape[0], -1)
layer_mask = mask['MaskedModule_0'] if mask else None
return masked.MaskedModule(
inputs,
features=self.NUM_FEATURES,
wrapped_module=flax.deprecated.nn.Dense,
mask=layer_mask,
<|code_end|>
, determine the next line of code. You have imports:
from typing import Any, Mapping, Optional
from absl.testing import absltest
from rigl.experimental.jax.pruning import init
from rigl.experimental.jax.pruning import masked
import flax
import jax
import jax.numpy as jnp
and context (class names, function names, or code) available:
# Path: rigl/experimental/jax/pruning/init.py
# def init(rng, shape, dtype=dtype):
# if mask is None:
# return base_init(rng, shape, dtype)
#
# # Find the ablated neurons in the mask, to determine correct fan_out.
# neuron_weight_count = jnp.sum(
# jnp.reshape(mask, (-1, mask.shape[-1])), axis=0)
# non_zero_neurons = jnp.sum(neuron_weight_count != 0)
#
# # Special case of completely ablated weight matrix/layer.
# if jnp.sum(non_zero_neurons) == 0:
# print('Empty weight mask!')
# return jnp.zeros(shape, dtype)
#
# # Neurons have different fan_in w/mask, build up initialization per-unit.
# init_cols = []
# rng, *split_rngs = jax.random.split(rng, mask.shape[-1] + 1)
# for i in range(mask.shape[-1]):
# # Special case of ablated neuron.
# if neuron_weight_count[i] == 0:
# init_cols.append(jnp.zeros(shape[:-1] + (1,), dtype))
# continue
#
# # Fake shape of weight matrix with correct fan_in, and fan_out.
# sparse_shape = (int(neuron_weight_count[i]), int(non_zero_neurons))
#
# # Use only the first column of init from initializer, since faked fan_out.
# init = base_init(split_rngs[i], sparse_shape, dtype)[Ellipsis, 0]
#
# # Expand out to full sparse array.
# expanded_init = jnp.zeros(
# mask[Ellipsis, i].shape,
# dtype).flatten().at[jnp.where(mask[Ellipsis, i].flatten() == 1)].set(init)
# expanded_init = jnp.reshape(expanded_init, mask[Ellipsis, i].shape)
# init_cols.append(expanded_init[Ellipsis, jnp.newaxis])
#
# return jnp.concatenate(init_cols, axis=-1)
#
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
. Output only the next line. | kernel_init=init.kaiming_sparse_normal( |
Next line prediction: <|code_start|>#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for weight_symmetry.pruning.init."""
class MaskedDense(flax.deprecated.nn.Module):
"""Single-layer Dense Masked Network."""
NUM_FEATURES: int = 32
def apply(self,
inputs,
mask = None):
inputs = inputs.reshape(inputs.shape[0], -1)
layer_mask = mask['MaskedModule_0'] if mask else None
<|code_end|>
. Use current file imports:
(from typing import Any, Mapping, Optional
from absl.testing import absltest
from rigl.experimental.jax.pruning import init
from rigl.experimental.jax.pruning import masked
import flax
import jax
import jax.numpy as jnp)
and context including class names, function names, or small code snippets from other files:
# Path: rigl/experimental/jax/pruning/init.py
# def init(rng, shape, dtype=dtype):
# if mask is None:
# return base_init(rng, shape, dtype)
#
# # Find the ablated neurons in the mask, to determine correct fan_out.
# neuron_weight_count = jnp.sum(
# jnp.reshape(mask, (-1, mask.shape[-1])), axis=0)
# non_zero_neurons = jnp.sum(neuron_weight_count != 0)
#
# # Special case of completely ablated weight matrix/layer.
# if jnp.sum(non_zero_neurons) == 0:
# print('Empty weight mask!')
# return jnp.zeros(shape, dtype)
#
# # Neurons have different fan_in w/mask, build up initialization per-unit.
# init_cols = []
# rng, *split_rngs = jax.random.split(rng, mask.shape[-1] + 1)
# for i in range(mask.shape[-1]):
# # Special case of ablated neuron.
# if neuron_weight_count[i] == 0:
# init_cols.append(jnp.zeros(shape[:-1] + (1,), dtype))
# continue
#
# # Fake shape of weight matrix with correct fan_in, and fan_out.
# sparse_shape = (int(neuron_weight_count[i]), int(non_zero_neurons))
#
# # Use only the first column of init from initializer, since faked fan_out.
# init = base_init(split_rngs[i], sparse_shape, dtype)[Ellipsis, 0]
#
# # Expand out to full sparse array.
# expanded_init = jnp.zeros(
# mask[Ellipsis, i].shape,
# dtype).flatten().at[jnp.where(mask[Ellipsis, i].flatten() == 1)].set(init)
# expanded_init = jnp.reshape(expanded_init, mask[Ellipsis, i].shape)
# init_cols.append(expanded_init[Ellipsis, jnp.newaxis])
#
# return jnp.concatenate(init_cols, axis=-1)
#
# Path: rigl/experimental/jax/pruning/masked.py
# def masked(module, mask):
# """Convenience function for masking a FLAX module with MaskedModule."""
# return MaskedModule.partial(wrapped_module=module, mask=mask)
. Output only the next line. | return masked.MaskedModule( |
Here is a snippet: <|code_start|>#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for weight_symmetry.shuffled_mask."""
class ShuffledMaskTest(absltest.TestCase):
def test_run_fc(self):
"""Tests if the driver for shuffled training runs correctly with FC NN."""
experiment_dir = tempfile.mkdtemp()
eval_flags = dict(
epochs=1,
experiment_dir=experiment_dir,
model='MNIST_FC',
)
with flagsaver.flagsaver(**eval_flags):
<|code_end|>
. Write the next line using the current file imports:
import glob
import tempfile
from os import path
from absl.testing import absltest
from absl.testing import flagsaver
from rigl.experimental.jax import shuffled_mask
and context from other files:
# Path: rigl/experimental/jax/shuffled_mask.py
# def main(argv: List[str]):
, which may include functions, classes, or code. Output only the next line. | shuffled_mask.main([]) |
Given snippet: <|code_start|> outputs. Useful to remove unnecessary dimensions for classification.
name: Optional scope for the variables.
global_pool: Optional boolean flag. If True, the input to the classification
layer is avgpooled to size 1x1, for any input size. (This is not part
of the original VGG architecture.)
pruning_method: String that specifies the pruning method used to identify
which weights to remove.
init_method: ('baseline', 'sparse', 'random_zeros') Whether to use standard
initialization or initialization that takes into the existing sparsity of
the layer. 'sparse' only makes sense when combined with
pruning_method == 'scratch'. 'random_zeros' set random weights to zero
using end_sparsoty parameter and used with 'baseline' method.
data_format: String specifying either "channels_first" for `[batch,
channels, height, width]` or "channels_last for `[batch, height, width,
channels]`.
width: Float multiplier of the number of filters in each layer.
prune_last_layer: Whether or not to prune the last layer.
end_sparsity: Desired sparsity at the end of training. Necessary to
initialize an already sparse network.
weight_decay: Weight for the l2 regularization loss.
Returns:
net: the output of the logits layer (if num_classes is a non-zero integer),
or the non-dropped-out input to the logits layer (if num_classes is 0 or
None).
end_points: a dict of tensors with intermediate activations. For
backwards compatibility, some Tensors appear multiple times in the dict.
"""
net_cfg = network_cfg[name]
sparse_conv2d = functools.partial(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import functools
import tensorflow.compat.v1 as tf
from rigl.imagenet_resnet import resnet_model
from tensorflow.contrib import layers
and context:
# Path: rigl/imagenet_resnet/resnet_model.py
# FLAGS = flags.FLAGS
# BATCH_NORM_DECAY = 0.9
# BATCH_NORM_EPSILON = 1e-5
# def batch_norm_relu(inputs, is_training, relu=True, init_zero=False,
# data_format='channels_first'):
# def fixed_padding(inputs, kernel_size, data_format='channels_first'):
# def __init__(self, sparsity, seed=None, dtype=tf.float32):
# def __call__(self, *args, **kwargs):
# def get_config(self):
# def __init__(self, sparsity, seed=None, dtype=tf.float32):
# def __call__(self, shape, dtype=None, partition_info=None):
# def get_config(self):
# def __init__(self, sparsity, seed=None, dtype=tf.float32):
# def __call__(self, shape, dtype=None, partition_info=None):
# def get_config(self):
# def _pick_initializer(kernel_initializer, init_method, pruning_method,
# end_sparsity):
# def conv2d_fixed_padding(inputs,
# filters,
# kernel_size,
# strides,
# pruning_method='baseline',
# init_method='baseline',
# data_format='channels_first',
# end_sparsity=0.,
# weight_decay=0.,
# init_scale=1.0,
# name=None):
# def residual_block_(inputs,
# filters,
# is_training,
# strides,
# use_projection=False,
# pruning_method='baseline',
# init_method='baseline',
# data_format='channels_first',
# end_sparsity=0.,
# weight_decay=0.,
# name=''):
# def bottleneck_block_(inputs,
# filters,
# is_training,
# strides,
# use_projection=False,
# pruning_method='baseline',
# init_method='baseline',
# data_format='channels_first',
# end_sparsity=0.,
# weight_decay=0.,
# name=None):
# def block_group(inputs,
# filters,
# block_fn,
# blocks,
# strides,
# is_training,
# name,
# pruning_method='baseline',
# init_method='baseline',
# data_format='channels_first',
# end_sparsity=0.,
# weight_decay=0.):
# def resnet_v1_generator(block_fn,
# num_blocks,
# num_classes,
# pruning_method='baseline',
# init_method='baseline',
# width=1.,
# prune_first_layer=True,
# prune_last_layer=True,
# data_format='channels_first',
# end_sparsity=0.,
# weight_decay=0.,
# name=None):
# def model(inputs, is_training):
# def resnet_v1_(resnet_depth,
# num_classes,
# pruning_method='baseline',
# init_method='baseline',
# width=1.,
# prune_first_layer=True,
# prune_last_layer=True,
# data_format='channels_first',
# end_sparsity=0.,
# weight_decay=0.,
# name=None):
# class RandomSparseInitializer(init_ops.Initializer):
# class SparseConvVarianceScalingInitializer(init_ops.Initializer):
# class SparseFCVarianceScalingInitializer(init_ops.Initializer):
which might include code, classes, or functions. Output only the next line. | resnet_model.conv2d_fixed_padding, |
Given the following code snippet before the placeholder: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for weight_symmetry.models.cifar10_cnn."""
class CIFAR10CNNTest(absltest.TestCase):
"""Tests the CIFAR10CNN model."""
def setUp(self):
super().setUp()
self._rng = jax.random.PRNGKey(42)
self._num_classes = 10
self._batch_size = 2
self._input_shape = ((self._batch_size, 32, 32, 3), jnp.float32)
self._input = jnp.zeros(*self._input_shape)
def test_output_shapes(self):
"""Tests the output shapes of the model."""
with flax.deprecated.nn.stateful() as initial_state:
<|code_end|>
, predict the next line using imports from the current file:
from absl.testing import absltest
from rigl.experimental.jax.models import cifar10_cnn
import flax
import jax
import jax.numpy as jnp
and context including class names, function names, and sometimes code from other files:
# Path: rigl/experimental/jax/models/cifar10_cnn.py
# class CIFAR10CNN(flax.deprecated.nn.Module):
# def apply(self,
# inputs,
# num_classes,
# filter_shape = (3, 3),
# filters = (32, 32, 64, 64, 128, 128),
# init_fn=flax.deprecated.nn.initializers.kaiming_normal,
# train=True,
# activation_fn = flax.deprecated.nn.relu,
# masks = None,
# masked_layer_indices = None):
. Output only the next line. | _, initial_params = cifar10_cnn.CIFAR10CNN.init_by_shape( |
Using the snippet: <|code_start|> pkfail(*args, **kwargs)
else:
pkfail('expect={} == actual={}', expect, actual)
def pkok(cond, fmt, *args, **kwargs):
"""If cond is not true, throw PKFail with calling context
Args:
cond (object): expression which should evaluate to true
fmt (str): to be passed to `string.format`
args (tuple): passed to format
kwargs (dict): passed to format
Returns:
object: `obj` value
"""
if not cond:
pkfail(fmt, *args, **kwargs)
return cond
def pkre(expect_re, actual, flags=re.IGNORECASE + re.DOTALL):
"""If actual does not match (re.search) expect_re, throw PKFail with calling context.
Args:
expect_re (object): string or re object
actual (object): run-time value
flags: passed on to re.search [IGNORECASE + DOTALL]
"""
<|code_end|>
, determine the next line of code. You have imports:
from pykern import pkcollections
from pykern import pkcompat
from pykern import pkinspect
from pykern import pkio
from pykern.pkdebug import pkdpretty
from pykern import pkyaml
from pykern.pkdebug import pkdexc
import contextlib
import importlib
import inspect
import json
import os
import py
import pytest
import re
import sys
import pykern.pkjson
import pykern.pkconst
import pykern.pkjinja
and context (class names, function names, or code) available:
# Path: pykern/pkcollections.py
# class PKDict(dict):
# class PKDictNameError(NameError):
# def __copy__(self):
# def __deepcopy__(self, memo):
# def __delattr__(self, name):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def copy(self):
# def pkdel(self, name, default=None):
# def pknested_get(self, dotted_key):
# def pksetdefault(self, *args, **kwargs):
# def pkunchecked_nested_get(self, dotted_key):
# def pkupdate(self, *args, **kwargs):
# def json_load_any(obj, *args, **kwargs):
# def object_pairs_hook(*args, **kwargs):
# def unchecked_del(obj, *keys):
#
# Path: pykern/pkcompat.py
# def locale_str(value):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def _assert_type(value, typ):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def unicode_unescape(value):
# def unicode_getcwd():
#
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
#
# Path: pykern/pkio.py
# TEXT_ENCODING = 'utf-8'
# def atomic_write(path, contents, **kwargs):
# def exception_is_not_found(exc):
# def expand_user_path(path):
# def has_file_extension(filename, to_check):
# def mkdir_parent(path):
# def mkdir_parent_only(path):
# def open_text(filename, **kwargs):
# def py_path(path=None):
# def random_base62(length=16):
# def read_binary(filename):
# def read_text(filename):
# def save_chdir(dirname, mkdir=False, is_pkunit_prefix=False):
# def sorted_glob(path, key=None):
# def _path_sort_attr(path):
# def unchecked_remove(*paths):
# def walk_tree(dirname, file_re=None):
# def _walk(dirname):
# def write_binary(path, contents):
# def write_text(path, contents):
. Output only the next line. | if not re.search(expect_re, pkcompat.from_bytes(actual), flags=flags): |
Next line prediction: <|code_start|> pkfail(*fmt_and_args, **kwargs)
def pkeq(expect, actual, *args, **kwargs):
"""If actual is not expect, throw assertion with calling context.
Opposite of `pkne`.
Args:
expect (object): what to test for
actual (object): run-time value
args (tuple): passed to pkfail()
kwargs (dict): passed to pkfail()
"""
if expect != actual:
if args or kwargs:
pkfail(*args, **kwargs)
else:
pkfail('expect={} != actual={}', expect, actual)
def pkfail(fmt, *args, **kwargs):
"""Format message and raise PKFail.
Args:
fmt (str): to be passed to `string.format`
args (tuple): passed to format
kwargs (dict): passed to format
"""
msg = fmt.format(*args, **kwargs)
<|code_end|>
. Use current file imports:
(from pykern import pkcollections
from pykern import pkcompat
from pykern import pkinspect
from pykern import pkio
from pykern.pkdebug import pkdpretty
from pykern import pkyaml
from pykern.pkdebug import pkdexc
import contextlib
import importlib
import inspect
import json
import os
import py
import pytest
import re
import sys
import pykern.pkjson
import pykern.pkconst
import pykern.pkjinja)
and context including class names, function names, or small code snippets from other files:
# Path: pykern/pkcollections.py
# class PKDict(dict):
# class PKDictNameError(NameError):
# def __copy__(self):
# def __deepcopy__(self, memo):
# def __delattr__(self, name):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def copy(self):
# def pkdel(self, name, default=None):
# def pknested_get(self, dotted_key):
# def pksetdefault(self, *args, **kwargs):
# def pkunchecked_nested_get(self, dotted_key):
# def pkupdate(self, *args, **kwargs):
# def json_load_any(obj, *args, **kwargs):
# def object_pairs_hook(*args, **kwargs):
# def unchecked_del(obj, *keys):
#
# Path: pykern/pkcompat.py
# def locale_str(value):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def _assert_type(value, typ):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def unicode_unescape(value):
# def unicode_getcwd():
#
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
#
# Path: pykern/pkio.py
# TEXT_ENCODING = 'utf-8'
# def atomic_write(path, contents, **kwargs):
# def exception_is_not_found(exc):
# def expand_user_path(path):
# def has_file_extension(filename, to_check):
# def mkdir_parent(path):
# def mkdir_parent_only(path):
# def open_text(filename, **kwargs):
# def py_path(path=None):
# def random_base62(length=16):
# def read_binary(filename):
# def read_text(filename):
# def save_chdir(dirname, mkdir=False, is_pkunit_prefix=False):
# def sorted_glob(path, key=None):
# def _path_sort_attr(path):
# def unchecked_remove(*paths):
# def walk_tree(dirname, file_re=None):
# def _walk(dirname):
# def write_binary(path, contents):
# def write_text(path, contents):
. Output only the next line. | call = pkinspect.caller(ignore_modules=[contextlib]) |
Continue the code snippet: <|code_start|>
#: Type of a regular expression
_RE_TYPE = type(re.compile(''))
#: _test_file initialized?
_init = False
#: module being run by `pykern.pkcli.test`
_test_file = None
class PKFail(AssertionError):
pass
def assert_object_with_json(basename, actual, ):
"""Converts actual to JSON and compares with data_dir/basename.json
Reads data_dir/basename.json and compares with actual
converted to json. Trailing newline is managed properly. The
keys are sorted and indentation is 4. actual written to work_dir.
Args:
expected_basename (str): file to be found in data_dir with json suffix
actual (object): to be serialized as json
"""
actual = pkdpretty(actual)
fn = '{}.json'.format(basename)
a = work_dir().join(fn)
<|code_end|>
. Use current file imports:
from pykern import pkcollections
from pykern import pkcompat
from pykern import pkinspect
from pykern import pkio
from pykern.pkdebug import pkdpretty
from pykern import pkyaml
from pykern.pkdebug import pkdexc
import contextlib
import importlib
import inspect
import json
import os
import py
import pytest
import re
import sys
import pykern.pkjson
import pykern.pkconst
import pykern.pkjinja
and context (classes, functions, or code) from other files:
# Path: pykern/pkcollections.py
# class PKDict(dict):
# class PKDictNameError(NameError):
# def __copy__(self):
# def __deepcopy__(self, memo):
# def __delattr__(self, name):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def copy(self):
# def pkdel(self, name, default=None):
# def pknested_get(self, dotted_key):
# def pksetdefault(self, *args, **kwargs):
# def pkunchecked_nested_get(self, dotted_key):
# def pkupdate(self, *args, **kwargs):
# def json_load_any(obj, *args, **kwargs):
# def object_pairs_hook(*args, **kwargs):
# def unchecked_del(obj, *keys):
#
# Path: pykern/pkcompat.py
# def locale_str(value):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def _assert_type(value, typ):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def unicode_unescape(value):
# def unicode_getcwd():
#
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
#
# Path: pykern/pkio.py
# TEXT_ENCODING = 'utf-8'
# def atomic_write(path, contents, **kwargs):
# def exception_is_not_found(exc):
# def expand_user_path(path):
# def has_file_extension(filename, to_check):
# def mkdir_parent(path):
# def mkdir_parent_only(path):
# def open_text(filename, **kwargs):
# def py_path(path=None):
# def random_base62(length=16):
# def read_binary(filename):
# def read_text(filename):
# def save_chdir(dirname, mkdir=False, is_pkunit_prefix=False):
# def sorted_glob(path, key=None):
# def _path_sort_attr(path):
# def unchecked_remove(*paths):
# def walk_tree(dirname, file_re=None):
# def _walk(dirname):
# def write_binary(path, contents):
# def write_text(path, contents):
. Output only the next line. | pkio.write_text(a, actual) |
Given snippet: <|code_start|> return _snip(r, len(obj))
def _object(obj, depth):
depth += 1
c = str(type(obj)()) if isinstance(obj, (list, tuple)) \
else '{}'
if depth > cfg.max_depth:
return c[0] + SNIP + c[1]
m = _dict if isinstance(obj, dict) else _sequence
return c[0] + m(obj, depth) + c[1]
def _redacted(key):
return isinstance(key, pkconst.STRING_TYPES) and SECRETS_RE.search(key) \
and REDACTED
def _sequence(obj, depth):
return _iterate(
obj,
lambda v: _format_arg(v, depth),
obj,
)
def _snip(truncated, count_of_original_elements):
truncated = truncated[:-2]
return truncated + ', ' + SNIP \
if count_of_original_elements > cfg.max_elements \
else truncated
def _string(value):
if r'\n' in value:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pykern import pkcompat
from pykern import pkconfig
from pykern import pkconst
from pykern import pkinspect
import datetime
import functools
import inspect
import json
import logging
import os
import pprint
import re
import six
import sys
import threading
import traceback
and context:
# Path: pykern/pkcompat.py
# def locale_str(value):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def _assert_type(value, typ):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def unicode_unescape(value):
# def unicode_getcwd():
#
# Path: pykern/pkconfig.py
# STRING_TYPES = pkconst.STRING_TYPES
# CHANNEL_ATTR = 'pykern_pkconfig_channel'
# KEY_RE = re.compile('^[a-z][a-z0-9_]*[a-z0-9]$', flags=re.IGNORECASE)
# TUPLE_SEP = ':'
# VALID_CHANNELS = ('dev', 'alpha', 'beta', 'prod')
# INTERNAL_TEST_CHANNELS = VALID_CHANNELS[0:2]
# CHANNEL_DEFAULT = VALID_CHANNELS[0]
# _PARSE_NONE_ATTR = 'pykern_pkconfig_parse_none'
# _PARSE_SECONDS = re.compile(
# r'^(?:(\d+)d)?(?:(?:(?:(\d+):)?(\d+):)?(\d+))?$',
# flags=re.IGNORECASE,
# )
# _PARSE_BYTES = re.compile(r'^(\d+)([kmgtp]?)b?$', flags=re.IGNORECASE)
# _PARSE_BYTES_MULTIPLIER = PKDict(
# k=1024,
# m=1024**2,
# g=1024**3,
# t=1024**4,
# )
# class ReplacedBy(tuple, object):
# class Required(tuple, object):
# class RequiredUnlessDev(tuple, object):
# class _Declaration(object):
# class _Key(str, object):
# def __new__(cls, new_name):
# def __new__(cls, *args):
# def __new__(cls, *args):
# def append_load_path(load_path):
# def channel_in(*args, **kwargs):
# def channel_in_internal_test(channel=None):
# def init(**kwargs):
# def flatten_values(base, new):
# def parse_none(func):
# def parse_bool(value):
# def parse_bytes(value):
# def parse_seconds(value):
# def parse_set(value):
# def parse_tuple(value):
# def raise_error(msg):
# def reset_state_for_testing(add_to_environ=None):
# def to_environ(cfg_keys, values=None, exclude_re=None):
# def a(k, v):
# def __init__(self, value):
# def _fixup_parser(self):
# def __new__(cls, parts):
# def _clean_environ():
# def _coalesce_values():
# def _flatten_keys(key_parts, values, res):
# def _iter_decls(decls, res):
# def _resolver(decl):
# def _resolve_dict(key, decl):
# def _resolve_list(key, decl):
# def _resolve_value(key, decl):
# def _z(msg):
#
# Path: pykern/pkconst.py
# STRING_TYPES = None
# STRING_TYPES = basestring
# STRING_TYPES = str
# PY_PATH_LOCAL_TYPE = type(py.path.local())
# BASE62_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
#
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
which might include code, classes, or functions. Output only the next line. | value = pkcompat.unicode_unescape(value) |
Based on the snippet: <|code_start|> if n == 'MainThread':
return 0
m = _THREAD_ID_RE.search(t.name)
if m:
return int(m.group(1))
return t.ident
def _write(self, fmt, args, kwargs, with_control=False):
"""Provides formatter for message to _process
Args:
fmt_or_record (str or LogRecord): how to format
args (list): what to format
kwargs (dict): what to format
with_control (bool): respect :attr:`control`
"""
def msg():
return pkdformat(fmt, *args, **kwargs)
def pid_time():
return (os.getpid(), datetime.datetime.utcnow())
def prefix():
return pkinspect.Call(
kwargs.get('pkdebug_frame') or inspect.currentframe().f_back.f_back.f_back.f_back,
)
self._process(prefix, msg, pid_time, with_control)
<|code_end|>
, predict the immediate next line with the help of imports:
from pykern import pkcompat
from pykern import pkconfig
from pykern import pkconst
from pykern import pkinspect
import datetime
import functools
import inspect
import json
import logging
import os
import pprint
import re
import six
import sys
import threading
import traceback
and context (classes, functions, sometimes code) from other files:
# Path: pykern/pkcompat.py
# def locale_str(value):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def _assert_type(value, typ):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def unicode_unescape(value):
# def unicode_getcwd():
#
# Path: pykern/pkconfig.py
# STRING_TYPES = pkconst.STRING_TYPES
# CHANNEL_ATTR = 'pykern_pkconfig_channel'
# KEY_RE = re.compile('^[a-z][a-z0-9_]*[a-z0-9]$', flags=re.IGNORECASE)
# TUPLE_SEP = ':'
# VALID_CHANNELS = ('dev', 'alpha', 'beta', 'prod')
# INTERNAL_TEST_CHANNELS = VALID_CHANNELS[0:2]
# CHANNEL_DEFAULT = VALID_CHANNELS[0]
# _PARSE_NONE_ATTR = 'pykern_pkconfig_parse_none'
# _PARSE_SECONDS = re.compile(
# r'^(?:(\d+)d)?(?:(?:(?:(\d+):)?(\d+):)?(\d+))?$',
# flags=re.IGNORECASE,
# )
# _PARSE_BYTES = re.compile(r'^(\d+)([kmgtp]?)b?$', flags=re.IGNORECASE)
# _PARSE_BYTES_MULTIPLIER = PKDict(
# k=1024,
# m=1024**2,
# g=1024**3,
# t=1024**4,
# )
# class ReplacedBy(tuple, object):
# class Required(tuple, object):
# class RequiredUnlessDev(tuple, object):
# class _Declaration(object):
# class _Key(str, object):
# def __new__(cls, new_name):
# def __new__(cls, *args):
# def __new__(cls, *args):
# def append_load_path(load_path):
# def channel_in(*args, **kwargs):
# def channel_in_internal_test(channel=None):
# def init(**kwargs):
# def flatten_values(base, new):
# def parse_none(func):
# def parse_bool(value):
# def parse_bytes(value):
# def parse_seconds(value):
# def parse_set(value):
# def parse_tuple(value):
# def raise_error(msg):
# def reset_state_for_testing(add_to_environ=None):
# def to_environ(cfg_keys, values=None, exclude_re=None):
# def a(k, v):
# def __init__(self, value):
# def _fixup_parser(self):
# def __new__(cls, parts):
# def _clean_environ():
# def _coalesce_values():
# def _flatten_keys(key_parts, values, res):
# def _iter_decls(decls, res):
# def _resolver(decl):
# def _resolve_dict(key, decl):
# def _resolve_list(key, decl):
# def _resolve_value(key, decl):
# def _z(msg):
#
# Path: pykern/pkconst.py
# STRING_TYPES = None
# STRING_TYPES = basestring
# STRING_TYPES = str
# PY_PATH_LOCAL_TYPE = type(py.path.local())
# BASE62_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
#
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
. Output only the next line. | @pkconfig.parse_none |
Given snippet: <|code_start|> Returns:
object: Redacted and truncated str or obj in exception
"""
def _dict(obj, depth):
return _iterate(
sorted(obj),
lambda k: _format_arg(k, depth) + ': ' \
+ (_redacted(k) or _format_arg(obj[k], depth)),
obj,
)
def _iterate(sequence, format_fn, obj):
r = ''
for i, v in enumerate(sequence):
if i >= cfg.max_elements:
break
r += format_fn(v) + ', '
return _snip(r, len(obj))
def _object(obj, depth):
depth += 1
c = str(type(obj)()) if isinstance(obj, (list, tuple)) \
else '{}'
if depth > cfg.max_depth:
return c[0] + SNIP + c[1]
m = _dict if isinstance(obj, dict) else _sequence
return c[0] + m(obj, depth) + c[1]
def _redacted(key):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pykern import pkcompat
from pykern import pkconfig
from pykern import pkconst
from pykern import pkinspect
import datetime
import functools
import inspect
import json
import logging
import os
import pprint
import re
import six
import sys
import threading
import traceback
and context:
# Path: pykern/pkcompat.py
# def locale_str(value):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def _assert_type(value, typ):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def unicode_unescape(value):
# def unicode_getcwd():
#
# Path: pykern/pkconfig.py
# STRING_TYPES = pkconst.STRING_TYPES
# CHANNEL_ATTR = 'pykern_pkconfig_channel'
# KEY_RE = re.compile('^[a-z][a-z0-9_]*[a-z0-9]$', flags=re.IGNORECASE)
# TUPLE_SEP = ':'
# VALID_CHANNELS = ('dev', 'alpha', 'beta', 'prod')
# INTERNAL_TEST_CHANNELS = VALID_CHANNELS[0:2]
# CHANNEL_DEFAULT = VALID_CHANNELS[0]
# _PARSE_NONE_ATTR = 'pykern_pkconfig_parse_none'
# _PARSE_SECONDS = re.compile(
# r'^(?:(\d+)d)?(?:(?:(?:(\d+):)?(\d+):)?(\d+))?$',
# flags=re.IGNORECASE,
# )
# _PARSE_BYTES = re.compile(r'^(\d+)([kmgtp]?)b?$', flags=re.IGNORECASE)
# _PARSE_BYTES_MULTIPLIER = PKDict(
# k=1024,
# m=1024**2,
# g=1024**3,
# t=1024**4,
# )
# class ReplacedBy(tuple, object):
# class Required(tuple, object):
# class RequiredUnlessDev(tuple, object):
# class _Declaration(object):
# class _Key(str, object):
# def __new__(cls, new_name):
# def __new__(cls, *args):
# def __new__(cls, *args):
# def append_load_path(load_path):
# def channel_in(*args, **kwargs):
# def channel_in_internal_test(channel=None):
# def init(**kwargs):
# def flatten_values(base, new):
# def parse_none(func):
# def parse_bool(value):
# def parse_bytes(value):
# def parse_seconds(value):
# def parse_set(value):
# def parse_tuple(value):
# def raise_error(msg):
# def reset_state_for_testing(add_to_environ=None):
# def to_environ(cfg_keys, values=None, exclude_re=None):
# def a(k, v):
# def __init__(self, value):
# def _fixup_parser(self):
# def __new__(cls, parts):
# def _clean_environ():
# def _coalesce_values():
# def _flatten_keys(key_parts, values, res):
# def _iter_decls(decls, res):
# def _resolver(decl):
# def _resolve_dict(key, decl):
# def _resolve_list(key, decl):
# def _resolve_value(key, decl):
# def _z(msg):
#
# Path: pykern/pkconst.py
# STRING_TYPES = None
# STRING_TYPES = basestring
# STRING_TYPES = str
# PY_PATH_LOCAL_TYPE = type(py.path.local())
# BASE62_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
#
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
which might include code, classes, or functions. Output only the next line. | return isinstance(key, pkconst.STRING_TYPES) and SECRETS_RE.search(key) \ |
Given the code snippet: <|code_start|> try:
return json.dumps(
obj,
sort_keys=True,
indent=4,
separators=(',', ': '),
) + '\n'
except Exception as e:
pass
if pprint.isreadable(obj):
return pprint.pformat(obj, indent=4) + '\n'
except Exception:
pass
return obj
class _LoggingHandler(logging.Handler):
"""Handler added to root logger.
"""
def emit(self, record):
"""Emit a log record via _printer
Writes all `logging.INFO` and above like `pkdp`, that is,
always. Below `logging.INFO` (i.e. DEBUG) is written like
`pkdc` using the same matching algorithms by converting
log records appropriately.
"""
wc = record.levelno < logging.INFO
_printer._process(
<|code_end|>
, generate the next line using the imports in this file:
from pykern import pkcompat
from pykern import pkconfig
from pykern import pkconst
from pykern import pkinspect
import datetime
import functools
import inspect
import json
import logging
import os
import pprint
import re
import six
import sys
import threading
import traceback
and context (functions, classes, or occasionally code) from other files:
# Path: pykern/pkcompat.py
# def locale_str(value):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def _assert_type(value, typ):
# def _locale_str(value):
# def _to_bytes(value):
# def _from_bytes(value):
# def unicode_unescape(value):
# def unicode_getcwd():
#
# Path: pykern/pkconfig.py
# STRING_TYPES = pkconst.STRING_TYPES
# CHANNEL_ATTR = 'pykern_pkconfig_channel'
# KEY_RE = re.compile('^[a-z][a-z0-9_]*[a-z0-9]$', flags=re.IGNORECASE)
# TUPLE_SEP = ':'
# VALID_CHANNELS = ('dev', 'alpha', 'beta', 'prod')
# INTERNAL_TEST_CHANNELS = VALID_CHANNELS[0:2]
# CHANNEL_DEFAULT = VALID_CHANNELS[0]
# _PARSE_NONE_ATTR = 'pykern_pkconfig_parse_none'
# _PARSE_SECONDS = re.compile(
# r'^(?:(\d+)d)?(?:(?:(?:(\d+):)?(\d+):)?(\d+))?$',
# flags=re.IGNORECASE,
# )
# _PARSE_BYTES = re.compile(r'^(\d+)([kmgtp]?)b?$', flags=re.IGNORECASE)
# _PARSE_BYTES_MULTIPLIER = PKDict(
# k=1024,
# m=1024**2,
# g=1024**3,
# t=1024**4,
# )
# class ReplacedBy(tuple, object):
# class Required(tuple, object):
# class RequiredUnlessDev(tuple, object):
# class _Declaration(object):
# class _Key(str, object):
# def __new__(cls, new_name):
# def __new__(cls, *args):
# def __new__(cls, *args):
# def append_load_path(load_path):
# def channel_in(*args, **kwargs):
# def channel_in_internal_test(channel=None):
# def init(**kwargs):
# def flatten_values(base, new):
# def parse_none(func):
# def parse_bool(value):
# def parse_bytes(value):
# def parse_seconds(value):
# def parse_set(value):
# def parse_tuple(value):
# def raise_error(msg):
# def reset_state_for_testing(add_to_environ=None):
# def to_environ(cfg_keys, values=None, exclude_re=None):
# def a(k, v):
# def __init__(self, value):
# def _fixup_parser(self):
# def __new__(cls, parts):
# def _clean_environ():
# def _coalesce_values():
# def _flatten_keys(key_parts, values, res):
# def _iter_decls(decls, res):
# def _resolver(decl):
# def _resolve_dict(key, decl):
# def _resolve_list(key, decl):
# def _resolve_value(key, decl):
# def _z(msg):
#
# Path: pykern/pkconst.py
# STRING_TYPES = None
# STRING_TYPES = basestring
# STRING_TYPES = str
# PY_PATH_LOCAL_TYPE = type(py.path.local())
# BASE62_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
#
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
. Output only the next line. | lambda: pkinspect.Call(record), |
Given the following code snippet before the placeholder: <|code_start|>
:copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
def default_command(*args):
"""Run tests one at a time with py.test.
Searches in ``tests`` sub-directory if not provided a
list of tests.
Arguments are directories or files, which are searched for _test.py
files.
An argument which is ``case=<pattern>``, is passed to pytest
as ``-k <pattern>``.
Writes failures to ``<base>_test.log``
Args:
args (str): test dirs, files, options
Returns:
str: passed=N if all passed, else raises `pkcli.Error`
"""
cfg = pkconfig.init(
max_failures=(5, int, 'maximum number of test failures before exit'),
)
<|code_end|>
, predict the next line using imports from the current file:
from pykern.pkcollections import PKDict
from pykern import pkcli
from pykern import pkconfig
from pykern import pksubprocess
from pykern import pkio
from pykern import pkunit
from pykern import pkio
import os
import sys
import re
and context including class names, function names, and sometimes code from other files:
# Path: pykern/pkcollections.py
# class PKDict(dict):
# """A subclass of dict that allows items to be read/written as attributes.
#
# The purpose of this is as a convenience in coding. You
# can refer to dictionary keys as attributes as long as they
# don't collide with the object's attributes. You should always
# use the `dict` interface to refer to the items of the dictionary
# programmatically, just like you would do with Javascript.
#
# You can reference any dict key as an attribute as long as it
# does not conflict with an attribute. For example, this works::
#
# x = PKDict()
# x.a = 1
# assert 1 == x.a
# x['a'] = 3
# assert 3 == x.a
# assert 'a' == x.keys()[0]
#
# You can't set an attribute that already exists. These calls throw
# exceptions::
#
# x.values = 1
# delattr(x, 'values')
#
# `dict` doesn't allow this anyway. However, you can't set or
# delete any existing attribute, even writable attributes. Indeed,
# you can't delete attributes at all. Subclasses should be "containers"
# only, not general objects.
# """
#
# def __copy__(self):
# return self.__class__(self)
#
# def __deepcopy__(self, memo):
# rv = self.copy()
# memo[id(rv)] = rv
# for k, v in rv.items():
# rv[copy.deepcopy(k, memo)] = copy.deepcopy(v, memo)
# return rv
#
# def __delattr__(self, name):
# raise PKDictNameError('{}: you cannot delete attributes', name)
#
# def __getattr__(self, name):
# if name in self:
# return self[name]
# # must match what CPython does exactly:
# # https://github.com/python/cpython/blob/d583738a87c3019dcfe06ed4a0002d1d6c9e9762/Objects/object.c#L899
# raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
#
# def __setattr__(self, name, value):
# if name in dir(self):
# raise PKDictNameError(
# '{}: invalid key for PKDict matches existing attribute'.format(name))
# super(PKDict, self).__setitem__(name, value)
#
# def copy(self):
# return self.__copy__()
#
# def pkdel(self, name, default=None):
# """Delete item if exists and return value
#
# The code will survive against concurrent access, but is not thread safe.
#
# Never throws KeyError.
#
# Args:
# name (object): item to delete
# Returns:
# object: value (if exists) or default
# """
# try:
# return self[name]
# except KeyError:
# return default
# finally:
# try:
# del self[name]
# except KeyError:
# pass
#
# def pknested_get(self, dotted_key):
# """Split key on dots and return nested get calls
#
# Throws KeyError if the dictionary key doesn't exist.
#
# Args:
# dotted_key (str): what
#
# Returns:
# object: value of element
# """
# d = self
# for k in dotted_key.split('.'):
# d = d[k]
# return d
#
# def pksetdefault(self, *args, **kwargs):
# """Get value or set it, possibly after evaluating arg.
#
# Must pass an even number of args or kwargs, but not both. Each pair
# is interpreted as (key, value).
#
# If self does not have `key`, then it will be set. If `value` is a callable,
# it will be called to get the value to set.
#
# Values will be called if they are callable
#
# Args:
# key (object): value to get or set
# value (object): if callable, will be called, else verbatim
# Returns:
# object: self
# """
# assert not (args and kwargs), \
# 'one of args or kwargs must be set, but not both'
# if args:
# assert len(args) % 2 == 0, \
# 'args must be an even number (pairs of key, value)'
# i = zip(args[0::2], args[1::2])
# else:
# i = kwargs.items()
# for k, v in i:
# if k not in self:
# self[k] = v() if callable(v) else v
# return self
#
# def pkunchecked_nested_get(self, dotted_key):
# """Split key on dots and return nested get calls
#
# If the element does not exist or is not indexable, fails silently with None.
#
# Args:
# dotted_key (str): what
#
# Returns:
# object: value of element or None
# """
# d = self
# for k in dotted_key.split('.'):
# try:
# d = d[k]
# except Exception:
# return None
# return d
#
# def pkupdate(self, *args, **kwargs):
# """Call `dict.update` and return ``self``.
# """
# super(PKDict, self).update(*args, **kwargs)
# return self
. Output only the next line. | e = PKDict(os.environ) |
Given snippet: <|code_start|> Returns:
bool: True if is a file not found exception.
"""
return isinstance(exc, IOError) and exc.errno == errno.ENOENT or isinstance(exc, py.error.ENOENT)
def expand_user_path(path):
"""Calls expanduser on path
If `pkunit_prefix` is set, will prefix, too.
Args:
path (str): path to expand
Returns:
py.path.Local: expanded path
"""
return py_path(path)
def has_file_extension(filename, to_check):
"""if matches any of the file extensions
Args:
filename (str|py.path.local): what to check
to_check (str|tuple|list): is without '.' and lower
Returns:
bool: if any of the extensions matches
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pykern import pkconst
from pykern import pkcompat
import contextlib
import errno
import glob
import io
import os
import os.path
import py
import random
import re
import shutil
and context:
# Path: pykern/pkconst.py
# STRING_TYPES = None
# STRING_TYPES = basestring
# STRING_TYPES = str
# PY_PATH_LOCAL_TYPE = type(py.path.local())
# BASE62_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
which might include code, classes, or functions. Output only the next line. | if isinstance(to_check, pkconst.STRING_TYPES): |
Given the code snippet: <|code_start|> a.append(p)
if os.path.exists(f):
return f
_raise_no_file_found(a, relative_filename)
def glob_paths(relative_path, caller_context=None, packages=None):
"""Find all paths that match the relative path in all packages
Args:
relative_path(str): Path relative to package_data directory.
caller_context (object): Any object from which to get the `root_package`.
packages (List[str]): Packages to search.
Returns:
py.path: absolute paths of the matched files
"""
r = []
a = []
for f, p in _files(relative_path, caller_context, packages):
a.append(p)
r.extend(glob.glob(f))
return [pkio.py_path(f) for f in r]
def _files(path, caller_context, packages):
if caller_context and packages:
raise ValueError(
f'Use only one of caller_context={caller_context} and packages={packages}',
)
for p in list(map(
<|code_end|>
, generate the next line using the imports in this file:
import errno
import glob
import importlib
import os.path
import pkg_resources
from pykern import pkinspect
from pykern import pkio
from pykern import pksetup
and context (functions, classes, or occasionally code) from other files:
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
#
# Path: pykern/pkio.py
# TEXT_ENCODING = 'utf-8'
# def atomic_write(path, contents, **kwargs):
# def exception_is_not_found(exc):
# def expand_user_path(path):
# def has_file_extension(filename, to_check):
# def mkdir_parent(path):
# def mkdir_parent_only(path):
# def open_text(filename, **kwargs):
# def py_path(path=None):
# def random_base62(length=16):
# def read_binary(filename):
# def read_text(filename):
# def save_chdir(dirname, mkdir=False, is_pkunit_prefix=False):
# def sorted_glob(path, key=None):
# def _path_sort_attr(path):
# def unchecked_remove(*paths):
# def walk_tree(dirname, file_re=None):
# def _walk(dirname):
# def write_binary(path, contents):
# def write_text(path, contents):
#
# Path: pykern/pksetup.py
# PACKAGE_DATA = 'package_data'
# TOX_INI_FILE = 'tox.ini'
# SCRIPTS_DIR = 'scripts'
# TESTS_DIR = 'tests'
# _VERSION_RE = r'(\d{8}\.\d+)'
# class NullCommand(distutils.cmd.Command, object):
# class PKDeploy(NullCommand):
# class SDist(setuptools.command.sdist.sdist, object):
# class Test(setuptools.command.test.test, object):
# class Tox(setuptools.Command, object):
# def initialize_options(*args, **kwargs):
# def finalize_options(*args, **kwargs):
# def run(*args, **kwargs):
# def run(self):
# def __assert_env(self, key, default=None):
# def __is_unique_version(self, fn, repo):
# def __run_cmd(self, cmd_name, **kwargs):
# def __run_twine(self, **kwargs):
# def check_readme(self, *args, **kwargs):
# def finalize_options(self):
# def run_tests(self):
# def initialize_options(self, *args, **kwargs):
# def finalize_options(self, *args, **kwargs):
# def run(self, *args, **kwargs):
# def _distribution_to_dict(self):
# def _pyenv(self, params):
# def install_requires():
# def setup(**kwargs):
# def _check_output(*args, **kwargs):
# def _entry_points(pkg_name):
# def _extras_require(base):
# def _find_files(dirname):
# def _git_exists():
# def _git_ls_files(extra_args):
# def _merge_kwargs(base, kwargs):
# def _packages(name):
# def _fullsplit(path, result=None):
# def _read(filename):
# def _readme():
# def _readthedocs_fixup():
# def _remove(path):
# def _sphinx_apidoc(base):
# def _state(base, kwargs):
# def _version(base):
# def _version_float(value):
# def _version_from_git(base):
# def _version_from_pkg_info(base):
# def _write(filename, content):
. Output only the next line. | lambda m: pkinspect.root_package(importlib.import_module(m)), |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
u"""Where external resources are stored
:copyright: Copyright (c) 2015 Bivio Software, Inc. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
# Root module: Import only builtin packages so avoid dependency issues
# TODO(e-carlin): discuss with rn if ok to import pkio
def file_path(relative_filename, caller_context=None, packages=None):
"""Return the path to the resource
Args:
relative_filename (str): file name relative to package_data directory.
caller_context (object): Any object from which to get the `root_package`
packages (List[str]): Packages to search.
Returns:
py.path: absolute path of the resource file
"""
<|code_end|>
, generate the next line using the imports in this file:
import errno
import glob
import importlib
import os.path
import pkg_resources
from pykern import pkinspect
from pykern import pkio
from pykern import pksetup
and context (functions, classes, or occasionally code) from other files:
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
#
# Path: pykern/pkio.py
# TEXT_ENCODING = 'utf-8'
# def atomic_write(path, contents, **kwargs):
# def exception_is_not_found(exc):
# def expand_user_path(path):
# def has_file_extension(filename, to_check):
# def mkdir_parent(path):
# def mkdir_parent_only(path):
# def open_text(filename, **kwargs):
# def py_path(path=None):
# def random_base62(length=16):
# def read_binary(filename):
# def read_text(filename):
# def save_chdir(dirname, mkdir=False, is_pkunit_prefix=False):
# def sorted_glob(path, key=None):
# def _path_sort_attr(path):
# def unchecked_remove(*paths):
# def walk_tree(dirname, file_re=None):
# def _walk(dirname):
# def write_binary(path, contents):
# def write_text(path, contents):
#
# Path: pykern/pksetup.py
# PACKAGE_DATA = 'package_data'
# TOX_INI_FILE = 'tox.ini'
# SCRIPTS_DIR = 'scripts'
# TESTS_DIR = 'tests'
# _VERSION_RE = r'(\d{8}\.\d+)'
# class NullCommand(distutils.cmd.Command, object):
# class PKDeploy(NullCommand):
# class SDist(setuptools.command.sdist.sdist, object):
# class Test(setuptools.command.test.test, object):
# class Tox(setuptools.Command, object):
# def initialize_options(*args, **kwargs):
# def finalize_options(*args, **kwargs):
# def run(*args, **kwargs):
# def run(self):
# def __assert_env(self, key, default=None):
# def __is_unique_version(self, fn, repo):
# def __run_cmd(self, cmd_name, **kwargs):
# def __run_twine(self, **kwargs):
# def check_readme(self, *args, **kwargs):
# def finalize_options(self):
# def run_tests(self):
# def initialize_options(self, *args, **kwargs):
# def finalize_options(self, *args, **kwargs):
# def run(self, *args, **kwargs):
# def _distribution_to_dict(self):
# def _pyenv(self, params):
# def install_requires():
# def setup(**kwargs):
# def _check_output(*args, **kwargs):
# def _entry_points(pkg_name):
# def _extras_require(base):
# def _find_files(dirname):
# def _git_exists():
# def _git_ls_files(extra_args):
# def _merge_kwargs(base, kwargs):
# def _packages(name):
# def _fullsplit(path, result=None):
# def _read(filename):
# def _readme():
# def _readthedocs_fixup():
# def _remove(path):
# def _sphinx_apidoc(base):
# def _state(base, kwargs):
# def _version(base):
# def _version_float(value):
# def _version_from_git(base):
# def _version_from_pkg_info(base):
# def _write(filename, content):
. Output only the next line. | return pkio.py_path(filename(relative_filename, caller_context, packages)) |
Predict the next line after this snippet: <|code_start|> Returns:
py.path: absolute paths of the matched files
"""
r = []
a = []
for f, p in _files(relative_path, caller_context, packages):
a.append(p)
r.extend(glob.glob(f))
return [pkio.py_path(f) for f in r]
def _files(path, caller_context, packages):
if caller_context and packages:
raise ValueError(
f'Use only one of caller_context={caller_context} and packages={packages}',
)
for p in list(map(
lambda m: pkinspect.root_package(importlib.import_module(m)),
packages or \
[pkinspect.root_package(caller_context if caller_context else pkinspect.caller_module())],
)):
# TODO(e-carlin): using pkg_resources is discouraged
# https://setuptools.readthedocs.io/en/latest/pkg_resources.html
# But, as of py3.7 importlib.resources doesn't offer a good API
# for accessing directories
# https://docs.python.org/3/library/importlib.html#module-importlib.resources
# https://gitlab.com/python-devs/importlib_resources/-/issues/58
yield (
pkg_resources.resource_filename(
p,
<|code_end|>
using the current file's imports:
import errno
import glob
import importlib
import os.path
import pkg_resources
from pykern import pkinspect
from pykern import pkio
from pykern import pksetup
and any relevant context from other files:
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
#
# Path: pykern/pkio.py
# TEXT_ENCODING = 'utf-8'
# def atomic_write(path, contents, **kwargs):
# def exception_is_not_found(exc):
# def expand_user_path(path):
# def has_file_extension(filename, to_check):
# def mkdir_parent(path):
# def mkdir_parent_only(path):
# def open_text(filename, **kwargs):
# def py_path(path=None):
# def random_base62(length=16):
# def read_binary(filename):
# def read_text(filename):
# def save_chdir(dirname, mkdir=False, is_pkunit_prefix=False):
# def sorted_glob(path, key=None):
# def _path_sort_attr(path):
# def unchecked_remove(*paths):
# def walk_tree(dirname, file_re=None):
# def _walk(dirname):
# def write_binary(path, contents):
# def write_text(path, contents):
#
# Path: pykern/pksetup.py
# PACKAGE_DATA = 'package_data'
# TOX_INI_FILE = 'tox.ini'
# SCRIPTS_DIR = 'scripts'
# TESTS_DIR = 'tests'
# _VERSION_RE = r'(\d{8}\.\d+)'
# class NullCommand(distutils.cmd.Command, object):
# class PKDeploy(NullCommand):
# class SDist(setuptools.command.sdist.sdist, object):
# class Test(setuptools.command.test.test, object):
# class Tox(setuptools.Command, object):
# def initialize_options(*args, **kwargs):
# def finalize_options(*args, **kwargs):
# def run(*args, **kwargs):
# def run(self):
# def __assert_env(self, key, default=None):
# def __is_unique_version(self, fn, repo):
# def __run_cmd(self, cmd_name, **kwargs):
# def __run_twine(self, **kwargs):
# def check_readme(self, *args, **kwargs):
# def finalize_options(self):
# def run_tests(self):
# def initialize_options(self, *args, **kwargs):
# def finalize_options(self, *args, **kwargs):
# def run(self, *args, **kwargs):
# def _distribution_to_dict(self):
# def _pyenv(self, params):
# def install_requires():
# def setup(**kwargs):
# def _check_output(*args, **kwargs):
# def _entry_points(pkg_name):
# def _extras_require(base):
# def _find_files(dirname):
# def _git_exists():
# def _git_ls_files(extra_args):
# def _merge_kwargs(base, kwargs):
# def _packages(name):
# def _fullsplit(path, result=None):
# def _read(filename):
# def _readme():
# def _readthedocs_fixup():
# def _remove(path):
# def _sphinx_apidoc(base):
# def _state(base, kwargs):
# def _version(base):
# def _version_float(value):
# def _version_from_git(base):
# def _version_from_pkg_info(base):
# def _write(filename, content):
. Output only the next line. | os.path.join(pksetup.PACKAGE_DATA, path), |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
u"""test `pykern.pkconfig`
:copyright: Copyright (c) 2015 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
def _custom_p6(v):
return dateutil.parser.parse(v)
<|code_end|>
with the help of current file imports:
from pykern import pkconfig
from pykern.pkdebug import pkdc, pkdp
import os
import dateutil.parser
and context from other files:
# Path: pykern/pkconfig.py
# STRING_TYPES = pkconst.STRING_TYPES
# CHANNEL_ATTR = 'pykern_pkconfig_channel'
# KEY_RE = re.compile('^[a-z][a-z0-9_]*[a-z0-9]$', flags=re.IGNORECASE)
# TUPLE_SEP = ':'
# VALID_CHANNELS = ('dev', 'alpha', 'beta', 'prod')
# INTERNAL_TEST_CHANNELS = VALID_CHANNELS[0:2]
# CHANNEL_DEFAULT = VALID_CHANNELS[0]
# _PARSE_NONE_ATTR = 'pykern_pkconfig_parse_none'
# _PARSE_SECONDS = re.compile(
# r'^(?:(\d+)d)?(?:(?:(?:(\d+):)?(\d+):)?(\d+))?$',
# flags=re.IGNORECASE,
# )
# _PARSE_BYTES = re.compile(r'^(\d+)([kmgtp]?)b?$', flags=re.IGNORECASE)
# _PARSE_BYTES_MULTIPLIER = PKDict(
# k=1024,
# m=1024**2,
# g=1024**3,
# t=1024**4,
# )
# class ReplacedBy(tuple, object):
# class Required(tuple, object):
# class RequiredUnlessDev(tuple, object):
# class _Declaration(object):
# class _Key(str, object):
# def __new__(cls, new_name):
# def __new__(cls, *args):
# def __new__(cls, *args):
# def append_load_path(load_path):
# def channel_in(*args, **kwargs):
# def channel_in_internal_test(channel=None):
# def init(**kwargs):
# def flatten_values(base, new):
# def parse_none(func):
# def parse_bool(value):
# def parse_bytes(value):
# def parse_seconds(value):
# def parse_set(value):
# def parse_tuple(value):
# def raise_error(msg):
# def reset_state_for_testing(add_to_environ=None):
# def to_environ(cfg_keys, values=None, exclude_re=None):
# def a(k, v):
# def __init__(self, value):
# def _fixup_parser(self):
# def __new__(cls, parts):
# def _clean_environ():
# def _coalesce_values():
# def _flatten_keys(key_parts, values, res):
# def _iter_decls(decls, res):
# def _resolver(decl):
# def _resolve_dict(key, decl):
# def _resolve_list(key, decl):
# def _resolve_value(key, decl):
# def _z(msg):
#
# Path: pykern/pkdebug.py
# def pkdc(fmt, *args, **kwargs):
# """Conditional print a message to `output` selectively based on `control`.
#
# Controlled output that you can leave in your code permanently.
#
# Args:
# fmt (str): how to :func:`str.format`
# args: what to format
# kwargs: what to format
# """
# # Since calls are left in for product, this check has
# # some value.
# if _have_control:
# _printer._write(fmt, args, kwargs, with_control=True)
#
# def pkdp(fmt_or_arg, *args, **kwargs):
# """Print a message to `output` unconditionally, possibly returning its arg
#
# Use for print statements in your code that you don't intend
# to keep in the system.
#
# Use `pkdlog` for permanent log messages.
#
# Args:
# fmt_or_arg (object): how to :func:`str.format`, or object to print
# args: what to format
# kwargs: what to format
#
# Returns:
# object: Will return fmt_or_arg, if args and kwargs are empty
# """
# if args or kwargs:
# _printer._write(fmt_or_arg, args, kwargs, with_control=False)
# else:
# _printer._write('{}', [fmt_or_arg], {}, with_control=False)
# return fmt_or_arg
, which may contain function names, class names, or code. Output only the next line. | @pkconfig.parse_none |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
u"""Helper functions for to :mod:`inspect`.
:copyright: Copyright (c) 2015 RadiaSoft, Inc. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
# Avoid pykern imports so avoid dependency issues for pkconfig
#: Used to simplify paths output
_start_dir = ''
try:
_start_dir = os.getcwd()
except Exception:
pass
_VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
<|code_end|>
, generate the next line using the imports in this file:
from pykern.pkcollections import PKDict
import inspect
import os
import os.path
import re
import sys
and context (functions, classes, or occasionally code) from other files:
# Path: pykern/pkcollections.py
# class PKDict(dict):
# """A subclass of dict that allows items to be read/written as attributes.
#
# The purpose of this is as a convenience in coding. You
# can refer to dictionary keys as attributes as long as they
# don't collide with the object's attributes. You should always
# use the `dict` interface to refer to the items of the dictionary
# programmatically, just like you would do with Javascript.
#
# You can reference any dict key as an attribute as long as it
# does not conflict with an attribute. For example, this works::
#
# x = PKDict()
# x.a = 1
# assert 1 == x.a
# x['a'] = 3
# assert 3 == x.a
# assert 'a' == x.keys()[0]
#
# You can't set an attribute that already exists. These calls throw
# exceptions::
#
# x.values = 1
# delattr(x, 'values')
#
# `dict` doesn't allow this anyway. However, you can't set or
# delete any existing attribute, even writable attributes. Indeed,
# you can't delete attributes at all. Subclasses should be "containers"
# only, not general objects.
# """
#
# def __copy__(self):
# return self.__class__(self)
#
# def __deepcopy__(self, memo):
# rv = self.copy()
# memo[id(rv)] = rv
# for k, v in rv.items():
# rv[copy.deepcopy(k, memo)] = copy.deepcopy(v, memo)
# return rv
#
# def __delattr__(self, name):
# raise PKDictNameError('{}: you cannot delete attributes', name)
#
# def __getattr__(self, name):
# if name in self:
# return self[name]
# # must match what CPython does exactly:
# # https://github.com/python/cpython/blob/d583738a87c3019dcfe06ed4a0002d1d6c9e9762/Objects/object.c#L899
# raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
#
# def __setattr__(self, name, value):
# if name in dir(self):
# raise PKDictNameError(
# '{}: invalid key for PKDict matches existing attribute'.format(name))
# super(PKDict, self).__setitem__(name, value)
#
# def copy(self):
# return self.__copy__()
#
# def pkdel(self, name, default=None):
# """Delete item if exists and return value
#
# The code will survive against concurrent access, but is not thread safe.
#
# Never throws KeyError.
#
# Args:
# name (object): item to delete
# Returns:
# object: value (if exists) or default
# """
# try:
# return self[name]
# except KeyError:
# return default
# finally:
# try:
# del self[name]
# except KeyError:
# pass
#
# def pknested_get(self, dotted_key):
# """Split key on dots and return nested get calls
#
# Throws KeyError if the dictionary key doesn't exist.
#
# Args:
# dotted_key (str): what
#
# Returns:
# object: value of element
# """
# d = self
# for k in dotted_key.split('.'):
# d = d[k]
# return d
#
# def pksetdefault(self, *args, **kwargs):
# """Get value or set it, possibly after evaluating arg.
#
# Must pass an even number of args or kwargs, but not both. Each pair
# is interpreted as (key, value).
#
# If self does not have `key`, then it will be set. If `value` is a callable,
# it will be called to get the value to set.
#
# Values will be called if they are callable
#
# Args:
# key (object): value to get or set
# value (object): if callable, will be called, else verbatim
# Returns:
# object: self
# """
# assert not (args and kwargs), \
# 'one of args or kwargs must be set, but not both'
# if args:
# assert len(args) % 2 == 0, \
# 'args must be an even number (pairs of key, value)'
# i = zip(args[0::2], args[1::2])
# else:
# i = kwargs.items()
# for k, v in i:
# if k not in self:
# self[k] = v() if callable(v) else v
# return self
#
# def pkunchecked_nested_get(self, dotted_key):
# """Split key on dots and return nested get calls
#
# If the element does not exist or is not indexable, fails silently with None.
#
# Args:
# dotted_key (str): what
#
# Returns:
# object: value of element or None
# """
# d = self
# for k in dotted_key.split('.'):
# try:
# d = d[k]
# except Exception:
# return None
# return d
#
# def pkupdate(self, *args, **kwargs):
# """Call `dict.update` and return ``self``.
# """
# super(PKDict, self).update(*args, **kwargs)
# return self
. Output only the next line. | class Call(PKDict): |
Here is a snippet: <|code_start|> # process starts. Then polling less frequently
# helps avoid thrashing, especially with mpi.
t = .5
return s
try:
stdout = output
if isinstance(output, six.string_types):
stdout = open(output, 'w')
stderr = subprocess.STDOUT if stdout else None
for sig in _SIGNALS:
signal.signal(sig, signal_handler)
p = subprocess.Popen(
cmd,
stdin=open(os.devnull),
stdout=stdout,
stderr=stderr,
env=env,
)
pid = p.pid
if msg:
msg('{}: started: {}', pid, cmd)
s = wait_pid()
p = None
if s != 0:
raise RuntimeError('error exit({})'.format(s))
if msg:
msg('{}: normal exit(0): {}', pid, cmd)
except Exception as e:
if msg:
<|code_end|>
. Write the next line using the current file imports:
from pykern.pkdebug import pkdc, pkdexc, pkdp
import os
import signal
import six
import subprocess
import threading
import psutil, time
and context from other files:
# Path: pykern/pkdebug.py
# def pkdc(fmt, *args, **kwargs):
# """Conditional print a message to `output` selectively based on `control`.
#
# Controlled output that you can leave in your code permanently.
#
# Args:
# fmt (str): how to :func:`str.format`
# args: what to format
# kwargs: what to format
# """
# # Since calls are left in for product, this check has
# # some value.
# if _have_control:
# _printer._write(fmt, args, kwargs, with_control=True)
#
# def pkdexc():
# """Return last exception and stack as a string
#
# Must be called from an ``except``. This function removes
# the last two calls from the stack. It joins the traceback
# so you get a complete stack trace.
#
# Will catch exceptions during the formatting and returns a
# string in all cases.
#
# Example::
#
# try:
# something
# except:
# pkdp(pkdexc())
#
# Returns:
# str: formatted exception and stack trace
# """
# try:
# e = sys.exc_info()
# if hasattr(traceback, 'TracebackException'):
# return ''.join(
# traceback.format_exception(*e) \
# + ['\nException was printed at:\n\n'] \
# + traceback.format_exception_only(e[0], e[1]) \
# + traceback.format_stack()[:-2],
# )
#
# else:
# return ''.join(
# traceback.format_exception_only(e[0], e[1]) \
# + traceback.format_stack()[:-2] \
# + traceback.format_tb(e[2]),
# )
#
# except Exception as e:
# return 'pykern.pkdebug.pkdexc: unable to retrieve exception info'
#
# def pkdp(fmt_or_arg, *args, **kwargs):
# """Print a message to `output` unconditionally, possibly returning its arg
#
# Use for print statements in your code that you don't intend
# to keep in the system.
#
# Use `pkdlog` for permanent log messages.
#
# Args:
# fmt_or_arg (object): how to :func:`str.format`, or object to print
# args: what to format
# kwargs: what to format
#
# Returns:
# object: Will return fmt_or_arg, if args and kwargs are empty
# """
# if args or kwargs:
# _printer._write(fmt_or_arg, args, kwargs, with_control=False)
# else:
# _printer._write('{}', [fmt_or_arg], {}, with_control=False)
# return fmt_or_arg
, which may include functions, classes, or code. Output only the next line. | msg('{}: exception: {} {}', pid, cmd, pkdexc()) |
Given snippet: <|code_start|>from __future__ import absolute_import, division, print_function
def render(out):
v = {'k1': 'v1'}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pykern import pkresource
from pykern import pkjinja
and context:
# Path: pykern/pkresource.py
# def file_path(relative_filename, caller_context=None, packages=None):
# def filename(relative_filename, caller_context=None, packages=None):
# def glob_paths(relative_path, caller_context=None, packages=None):
# def _files(path, caller_context, packages):
# def _raise_no_file_found(packages, path):
#
# Path: pykern/pkjinja.py
# RESOURCE_SUFFIX = '.jinja'
# def render_file(filename, j2_ctx, output=None, strict_undefined=False, jinja_env=None):
# def render_resource(basename, *args, **kwargs):
which might include code, classes, or functions. Output only the next line. | return pkjinja.render_resource('t1', v, out) |
Next line prediction: <|code_start|> Returns:
float: current value of the average
"""
assert self.average is not None, \
'self.average is None and has not been initialized'
return self.average
def _Privy(object):
"""This is a private class that does nothing"""
pass
def _cfg_length(anything):
"""Configuration parser for any_length
Args:
anything (object): configured value
Returns:
int: value between 1 and 999
"""
anything = int(anything)
assert 0 < anything <= 999, \
'{}: any_length must be from 1 to 999'
return anything
# Finally we assign any length. Note that we include a trailing , at the
# end of every line in a list so that you don't have to remember to
# add the comma when you add another line.
<|code_end|>
. Use current file imports:
(from pykern import pkconfig
from pykern.pkdebug import pkdc, pkdp)
and context including class names, function names, or small code snippets from other files:
# Path: pykern/pkconfig.py
# STRING_TYPES = pkconst.STRING_TYPES
# CHANNEL_ATTR = 'pykern_pkconfig_channel'
# KEY_RE = re.compile('^[a-z][a-z0-9_]*[a-z0-9]$', flags=re.IGNORECASE)
# TUPLE_SEP = ':'
# VALID_CHANNELS = ('dev', 'alpha', 'beta', 'prod')
# INTERNAL_TEST_CHANNELS = VALID_CHANNELS[0:2]
# CHANNEL_DEFAULT = VALID_CHANNELS[0]
# _PARSE_NONE_ATTR = 'pykern_pkconfig_parse_none'
# _PARSE_SECONDS = re.compile(
# r'^(?:(\d+)d)?(?:(?:(?:(\d+):)?(\d+):)?(\d+))?$',
# flags=re.IGNORECASE,
# )
# _PARSE_BYTES = re.compile(r'^(\d+)([kmgtp]?)b?$', flags=re.IGNORECASE)
# _PARSE_BYTES_MULTIPLIER = PKDict(
# k=1024,
# m=1024**2,
# g=1024**3,
# t=1024**4,
# )
# class ReplacedBy(tuple, object):
# class Required(tuple, object):
# class RequiredUnlessDev(tuple, object):
# class _Declaration(object):
# class _Key(str, object):
# def __new__(cls, new_name):
# def __new__(cls, *args):
# def __new__(cls, *args):
# def append_load_path(load_path):
# def channel_in(*args, **kwargs):
# def channel_in_internal_test(channel=None):
# def init(**kwargs):
# def flatten_values(base, new):
# def parse_none(func):
# def parse_bool(value):
# def parse_bytes(value):
# def parse_seconds(value):
# def parse_set(value):
# def parse_tuple(value):
# def raise_error(msg):
# def reset_state_for_testing(add_to_environ=None):
# def to_environ(cfg_keys, values=None, exclude_re=None):
# def a(k, v):
# def __init__(self, value):
# def _fixup_parser(self):
# def __new__(cls, parts):
# def _clean_environ():
# def _coalesce_values():
# def _flatten_keys(key_parts, values, res):
# def _iter_decls(decls, res):
# def _resolver(decl):
# def _resolve_dict(key, decl):
# def _resolve_list(key, decl):
# def _resolve_value(key, decl):
# def _z(msg):
#
# Path: pykern/pkdebug.py
# def pkdc(fmt, *args, **kwargs):
# """Conditional print a message to `output` selectively based on `control`.
#
# Controlled output that you can leave in your code permanently.
#
# Args:
# fmt (str): how to :func:`str.format`
# args: what to format
# kwargs: what to format
# """
# # Since calls are left in for product, this check has
# # some value.
# if _have_control:
# _printer._write(fmt, args, kwargs, with_control=True)
#
# def pkdp(fmt_or_arg, *args, **kwargs):
# """Print a message to `output` unconditionally, possibly returning its arg
#
# Use for print statements in your code that you don't intend
# to keep in the system.
#
# Use `pkdlog` for permanent log messages.
#
# Args:
# fmt_or_arg (object): how to :func:`str.format`, or object to print
# args: what to format
# kwargs: what to format
#
# Returns:
# object: Will return fmt_or_arg, if args and kwargs are empty
# """
# if args or kwargs:
# _printer._write(fmt_or_arg, args, kwargs, with_control=False)
# else:
# _printer._write('{}', [fmt_or_arg], {}, with_control=False)
# return fmt_or_arg
. Output only the next line. | cfg = pkconfig.init( |
Given the following code snippet before the placeholder: <|code_start|> str: rendered template
"""
t = pkio.read_text(filename)
kw = dict(
trim_blocks=True,
lstrip_blocks=True,
keep_trailing_newline=True,
extensions=['jinja2.ext.do'],
)
if strict_undefined:
kw['undefined'] = jinja2.StrictUndefined
if jinja_env:
kw.update(jinja_env)
je = jinja2.Environment(**kw)
res = je.from_string(t).render(j2_ctx)
if output:
pkio.write_text(output, res)
return res
def render_resource(basename, *args, **kwargs):
"""Render a pkresource as a jinja template.
Args:
basename (str): name without `RESOURCE_SUFFIX`
args (list): see func:`render_file` for rest of args and return
"""
return render_file(
pkresource.filename(
basename + RESOURCE_SUFFIX,
<|code_end|>
, predict the next line using imports from the current file:
from pykern import pkinspect
from pykern import pkio
from pykern import pkresource
from pykern.pkdebug import pkdc, pkdp
import jinja2
and context including class names, function names, and sometimes code from other files:
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
#
# Path: pykern/pkio.py
# TEXT_ENCODING = 'utf-8'
# def atomic_write(path, contents, **kwargs):
# def exception_is_not_found(exc):
# def expand_user_path(path):
# def has_file_extension(filename, to_check):
# def mkdir_parent(path):
# def mkdir_parent_only(path):
# def open_text(filename, **kwargs):
# def py_path(path=None):
# def random_base62(length=16):
# def read_binary(filename):
# def read_text(filename):
# def save_chdir(dirname, mkdir=False, is_pkunit_prefix=False):
# def sorted_glob(path, key=None):
# def _path_sort_attr(path):
# def unchecked_remove(*paths):
# def walk_tree(dirname, file_re=None):
# def _walk(dirname):
# def write_binary(path, contents):
# def write_text(path, contents):
#
# Path: pykern/pkresource.py
# def file_path(relative_filename, caller_context=None, packages=None):
# def filename(relative_filename, caller_context=None, packages=None):
# def glob_paths(relative_path, caller_context=None, packages=None):
# def _files(path, caller_context, packages):
# def _raise_no_file_found(packages, path):
#
# Path: pykern/pkdebug.py
# def pkdc(fmt, *args, **kwargs):
# """Conditional print a message to `output` selectively based on `control`.
#
# Controlled output that you can leave in your code permanently.
#
# Args:
# fmt (str): how to :func:`str.format`
# args: what to format
# kwargs: what to format
# """
# # Since calls are left in for product, this check has
# # some value.
# if _have_control:
# _printer._write(fmt, args, kwargs, with_control=True)
#
# def pkdp(fmt_or_arg, *args, **kwargs):
# """Print a message to `output` unconditionally, possibly returning its arg
#
# Use for print statements in your code that you don't intend
# to keep in the system.
#
# Use `pkdlog` for permanent log messages.
#
# Args:
# fmt_or_arg (object): how to :func:`str.format`, or object to print
# args: what to format
# kwargs: what to format
#
# Returns:
# object: Will return fmt_or_arg, if args and kwargs are empty
# """
# if args or kwargs:
# _printer._write(fmt_or_arg, args, kwargs, with_control=False)
# else:
# _printer._write('{}', [fmt_or_arg], {}, with_control=False)
# return fmt_or_arg
. Output only the next line. | pkinspect.caller_module(), |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
u"""Simplify rendering jinja2
:copyright: Copyright (c) 2015 Bivio Software, Inc. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
#: Implicit extension including '.' added to resources
RESOURCE_SUFFIX = '.jinja'
def render_file(filename, j2_ctx, output=None, strict_undefined=False, jinja_env=None):
"""Render filename as template with j2_ctx.
Args:
basename (str): name without jinja extension
j2_ctx (dict): how to replace values in Jinja2 template
output (str): file name of output; if None, return str
strict_undefined (bool): set `jinja2.StrictUndefined` if True
jinja_env (dict): add values to jinja2 environment
Returns:
str: rendered template
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pykern import pkinspect
from pykern import pkio
from pykern import pkresource
from pykern.pkdebug import pkdc, pkdp
import jinja2
and context:
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
#
# Path: pykern/pkio.py
# TEXT_ENCODING = 'utf-8'
# def atomic_write(path, contents, **kwargs):
# def exception_is_not_found(exc):
# def expand_user_path(path):
# def has_file_extension(filename, to_check):
# def mkdir_parent(path):
# def mkdir_parent_only(path):
# def open_text(filename, **kwargs):
# def py_path(path=None):
# def random_base62(length=16):
# def read_binary(filename):
# def read_text(filename):
# def save_chdir(dirname, mkdir=False, is_pkunit_prefix=False):
# def sorted_glob(path, key=None):
# def _path_sort_attr(path):
# def unchecked_remove(*paths):
# def walk_tree(dirname, file_re=None):
# def _walk(dirname):
# def write_binary(path, contents):
# def write_text(path, contents):
#
# Path: pykern/pkresource.py
# def file_path(relative_filename, caller_context=None, packages=None):
# def filename(relative_filename, caller_context=None, packages=None):
# def glob_paths(relative_path, caller_context=None, packages=None):
# def _files(path, caller_context, packages):
# def _raise_no_file_found(packages, path):
#
# Path: pykern/pkdebug.py
# def pkdc(fmt, *args, **kwargs):
# """Conditional print a message to `output` selectively based on `control`.
#
# Controlled output that you can leave in your code permanently.
#
# Args:
# fmt (str): how to :func:`str.format`
# args: what to format
# kwargs: what to format
# """
# # Since calls are left in for product, this check has
# # some value.
# if _have_control:
# _printer._write(fmt, args, kwargs, with_control=True)
#
# def pkdp(fmt_or_arg, *args, **kwargs):
# """Print a message to `output` unconditionally, possibly returning its arg
#
# Use for print statements in your code that you don't intend
# to keep in the system.
#
# Use `pkdlog` for permanent log messages.
#
# Args:
# fmt_or_arg (object): how to :func:`str.format`, or object to print
# args: what to format
# kwargs: what to format
#
# Returns:
# object: Will return fmt_or_arg, if args and kwargs are empty
# """
# if args or kwargs:
# _printer._write(fmt_or_arg, args, kwargs, with_control=False)
# else:
# _printer._write('{}', [fmt_or_arg], {}, with_control=False)
# return fmt_or_arg
which might include code, classes, or functions. Output only the next line. | t = pkio.read_text(filename) |
Predict the next line for this snippet: <|code_start|>
Returns:
str: rendered template
"""
t = pkio.read_text(filename)
kw = dict(
trim_blocks=True,
lstrip_blocks=True,
keep_trailing_newline=True,
extensions=['jinja2.ext.do'],
)
if strict_undefined:
kw['undefined'] = jinja2.StrictUndefined
if jinja_env:
kw.update(jinja_env)
je = jinja2.Environment(**kw)
res = je.from_string(t).render(j2_ctx)
if output:
pkio.write_text(output, res)
return res
def render_resource(basename, *args, **kwargs):
"""Render a pkresource as a jinja template.
Args:
basename (str): name without `RESOURCE_SUFFIX`
args (list): see func:`render_file` for rest of args and return
"""
return render_file(
<|code_end|>
with the help of current file imports:
from pykern import pkinspect
from pykern import pkio
from pykern import pkresource
from pykern.pkdebug import pkdc, pkdp
import jinja2
and context from other files:
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
#
# Path: pykern/pkio.py
# TEXT_ENCODING = 'utf-8'
# def atomic_write(path, contents, **kwargs):
# def exception_is_not_found(exc):
# def expand_user_path(path):
# def has_file_extension(filename, to_check):
# def mkdir_parent(path):
# def mkdir_parent_only(path):
# def open_text(filename, **kwargs):
# def py_path(path=None):
# def random_base62(length=16):
# def read_binary(filename):
# def read_text(filename):
# def save_chdir(dirname, mkdir=False, is_pkunit_prefix=False):
# def sorted_glob(path, key=None):
# def _path_sort_attr(path):
# def unchecked_remove(*paths):
# def walk_tree(dirname, file_re=None):
# def _walk(dirname):
# def write_binary(path, contents):
# def write_text(path, contents):
#
# Path: pykern/pkresource.py
# def file_path(relative_filename, caller_context=None, packages=None):
# def filename(relative_filename, caller_context=None, packages=None):
# def glob_paths(relative_path, caller_context=None, packages=None):
# def _files(path, caller_context, packages):
# def _raise_no_file_found(packages, path):
#
# Path: pykern/pkdebug.py
# def pkdc(fmt, *args, **kwargs):
# """Conditional print a message to `output` selectively based on `control`.
#
# Controlled output that you can leave in your code permanently.
#
# Args:
# fmt (str): how to :func:`str.format`
# args: what to format
# kwargs: what to format
# """
# # Since calls are left in for product, this check has
# # some value.
# if _have_control:
# _printer._write(fmt, args, kwargs, with_control=True)
#
# def pkdp(fmt_or_arg, *args, **kwargs):
# """Print a message to `output` unconditionally, possibly returning its arg
#
# Use for print statements in your code that you don't intend
# to keep in the system.
#
# Use `pkdlog` for permanent log messages.
#
# Args:
# fmt_or_arg (object): how to :func:`str.format`, or object to print
# args: what to format
# kwargs: what to format
#
# Returns:
# object: Will return fmt_or_arg, if args and kwargs are empty
# """
# if args or kwargs:
# _printer._write(fmt_or_arg, args, kwargs, with_control=False)
# else:
# _printer._write('{}', [fmt_or_arg], {}, with_control=False)
# return fmt_or_arg
, which may contain function names, class names, or code. Output only the next line. | pkresource.filename( |
Next line prediction: <|code_start|>class C():
pass
v = 1
c = C()
def caller(ignore_modules=None):
<|code_end|>
. Use current file imports:
(from pykern import pkinspect)
and context including class names, function names, or small code snippets from other files:
# Path: pykern/pkinspect.py
# _VALID_IDENTIFIER_RE = re.compile(r'^[a-z_]\w*$', re.IGNORECASE)
# class Call(PKDict):
# def __init__(self, frame_or_log):
# def __str__(self):
# def caller(ignore_modules=None, exclude_first=True):
# def caller_module(exclude_first=True):
# def is_caller_main():
# def is_valid_identifier(string):
# def module_basename(obj):
# def module_name_join(names):
# def module_name_split(obj):
# def module_functions(func_prefix, module=None):
# def root_package(obj):
# def submodule_name(obj):
# def this_module():
. Output only the next line. | return pkinspect.caller(ignore_modules=ignore_modules) |
Based on the snippet: <|code_start|>
def index(request):
messages.debug(request, f'Test: {getattr(manager, "test", None)}')
messages.debug(request, '%s SQL statements were executed.' % 666)
messages.info(request, 'Three credits remain in your account.')
messages.success(request, 'Profile details updated.')
messages.warning(request, 'Your account expires in three days.')
messages.error(request, 'Document deleted.')
return render(request, 'adminlte_full/base.html')
# return render(request, 'breadcrumbs_demo.html')
def profile(request):
return render(request, 'adminlte_full/base.html')
def terms(request):
return render(request, 'terms.html')
@manager.menu_loader
class MyMenuLoader(MenuLoader):
def __call__(self, program_name):
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import datetime, timedelta
from django.contrib import auth, messages
from django.shortcuts import render
from django import forms
from django.http import JsonResponse
from django.urls import reverse_lazy
from adminlte_base import MenuLoader, MenuItem, Message, Notification, Task, Dropdown, ThemeColor
from adminlte_full.adminlte import manager
from adminlte_full.models import MenuModel
and context (classes, functions, sometimes code) from other files:
# Path: adminlte_full/adminlte.py
# class ConfigWrapper(object):
# class Manager(AbstractManager):
# def get(self, name, default=''):
# def create_url(self, endpoint, *endpoint_args, **endpoint_kwargs):
# def get_flash_messages(self):
# def static(self, filename):
#
# Path: adminlte_full/models.py
# class MenuModel(models.Model, MenuMixin):
# title = models.CharField(max_length=500)
# program_name = models.CharField(max_length=255, unique=True)
#
# @property
# def items(self):
# return self.menuitemmodel_set.select_related('parent')
#
# def __str__(self):
# return f'{self.title} [{self.program_name}]'
. Output only the next line. | return MenuModel.objects.get(program_name=program_name) |
Here is a snippet: <|code_start|>
try:
except ImportError:
def gravatar(email, size=200):
return 'https://www.gravatar.com/avatar/{}?{}'.format(
md5(email.lower().encode('utf-8')).hexdigest(),
urlencode({
's': str(size)
})
)
def environment(**options):
env = Environment(**options)
for name in filters.__all__:
env.filters.setdefault(name, getattr(filters, name))
env.filters.setdefault('gravatar', gravatar)
env.globals.update({
'static': static,
'url': reverse,
<|code_end|>
. Write the next line using the current file imports:
from adminlte_base import filters
from adminlte_base import ThemeColor, ThemeLayout
from django.templatetags.static import static
from django.urls import reverse
from jinja2 import Environment
from .adminlte import manager
from hashlib import md5
from urllib import urlencode
from urllib.parse import urlencode
and context from other files:
# Path: adminlte_full/adminlte.py
# class ConfigWrapper(object):
# class Manager(AbstractManager):
# def get(self, name, default=''):
# def create_url(self, endpoint, *endpoint_args, **endpoint_kwargs):
# def get_flash_messages(self):
# def static(self, filename):
, which may include functions, classes, or code. Output only the next line. | 'adminlte': manager, |
Continue the code snippet: <|code_start|>try:
except ImportError:
register = template.Library()
for name in filters.__all__:
register.filter(name, getattr(filters, name))
@register.filter
def gravatar(email, size=200):
return 'https://www.gravatar.com/avatar/{}?{}'.format(
md5(email.lower().encode('utf-8')).hexdigest(),
urlencode({
's': str(size)
})
)
@register.filter
def humanize(dt):
<|code_end|>
. Use current file imports:
from hashlib import md5
from urllib import urlencode
from urllib.parse import urlencode
from adminlte_base import filters
from django import template
from django.template import Node
from django.template.base import TemplateSyntaxError, kwarg_re
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from ..adminlte import config
from ..adminlte import manager
and context (classes, functions, or code) from other files:
# Path: adminlte_full/adminlte.py
# class ConfigWrapper(object):
# class Manager(AbstractManager):
# def get(self, name, default=''):
# def create_url(self, endpoint, *endpoint_args, **endpoint_kwargs):
# def get_flash_messages(self):
# def static(self, filename):
#
# Path: adminlte_full/adminlte.py
# class ConfigWrapper(object):
# class Manager(AbstractManager):
# def get(self, name, default=''):
# def create_url(self, endpoint, *endpoint_args, **endpoint_kwargs):
# def get_flash_messages(self):
# def static(self, filename):
. Output only the next line. | locale = config.get( |
Based on the snippet: <|code_start|>
@register.filter
def gravatar(email, size=200):
return 'https://www.gravatar.com/avatar/{}?{}'.format(
md5(email.lower().encode('utf-8')).hexdigest(),
urlencode({
's': str(size)
})
)
@register.filter
def humanize(dt):
locale = config.get(
'LOCALE_NAME', config.get('LANGUAGE_CODE').replace('-', '_')
)
time_zone = config.get('TIME_ZONE', None)
return filters.humanize(dt, locale, time_zone)
simple_tag = method_decorator(register.simple_tag)
@register.simple_tag(
name='adminlte.get_home_page',
takes_context=True
)
def get_home_page(context):
"""Returns a link to the home page as a named tuple with url and title fields."""
<|code_end|>
, predict the immediate next line with the help of imports:
from hashlib import md5
from urllib import urlencode
from urllib.parse import urlencode
from adminlte_base import filters
from django import template
from django.template import Node
from django.template.base import TemplateSyntaxError, kwarg_re
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from ..adminlte import config
from ..adminlte import manager
and context (classes, functions, sometimes code) from other files:
# Path: adminlte_full/adminlte.py
# class ConfigWrapper(object):
# class Manager(AbstractManager):
# def get(self, name, default=''):
# def create_url(self, endpoint, *endpoint_args, **endpoint_kwargs):
# def get_flash_messages(self):
# def static(self, filename):
#
# Path: adminlte_full/adminlte.py
# class ConfigWrapper(object):
# class Manager(AbstractManager):
# def get(self, name, default=''):
# def create_url(self, endpoint, *endpoint_args, **endpoint_kwargs):
# def get_flash_messages(self):
# def static(self, filename):
. Output only the next line. | return manager.with_context(context).get_home_page() |
Given snippet: <|code_start|> "It is either read-protected or not readable by the server."
)
@requires_csrf_token
def handler404(request, exception):
return error_page(
request, 404, 'Page not found',
'The requested URL was not found on the server.'
'If you entered the URL manually please check your spelling and try again.'
)
@requires_csrf_token
def handler500(request):
return error_page(
request, 500, 'Internal Server Error',
'The server encountered an internal error and was unable to complete your request.'
'Either the server is overloaded or there is an error in the application.'
)
class LoginView(auth_views.LoginView):
form_class = AuthenticationForm
template_name = 'adminlte_full/login.html'
class PasswordChangeView(auth_views.PasswordChangeView):
form_class = PasswordChangeForm
template_name = 'adminlte_full/change_password.html'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib import messages
from django.contrib.auth import views as auth_views
from django.shortcuts import render
from django.views.decorators.csrf import requires_csrf_token
from django.urls.base import reverse_lazy
from django.utils.translation import gettext_lazy as _
from .adminlte import config
from .forms import *
and context:
# Path: adminlte_full/adminlte.py
# class ConfigWrapper(object):
# class Manager(AbstractManager):
# def get(self, name, default=''):
# def create_url(self, endpoint, *endpoint_args, **endpoint_kwargs):
# def get_flash_messages(self):
# def static(self, filename):
which might include code, classes, or functions. Output only the next line. | success_url = reverse_lazy(config['ADMINLTE_LOGIN_ENDPOINT']) |
Predict the next line for this snippet: <|code_start|> description='Convert DNA or AA FASTA to AA ORF-only FASTA',
epilog=('Given DNA or AA FASTA on stdin, output AA ORF-only FASTA to '
'stdout. Optionally, filter by minimum required ORF length '
'and allow the output of short ORFs that are open.'))
parser.add_argument(
'--allowOpenORFs', default=False, action='store_true',
help=('If True, ORFs that do not meet the length requirement '
'(as specified by --minORFLength) will be output as long as '
'they are open.'))
parser.add_argument(
'--minORFLength', metavar='LEN', type=int, default=None,
help='Only ORFs of at least this length will be written to stdout.')
parser.add_argument(
'--maxORFLength', metavar='LEN', type=int, default=None,
help=('Only ORFs of a maximum of this length will be written to '
'stdout.'))
parser.add_argument(
'--kozakOnly', default=False, action='store_true',
help=('Only ORFs that also have a Kozak consensus will be written to '
'stdout. Only applicable if DNA reads are given.'))
parser.add_argument(
'--kozakInfoFile',
help=('Filename to which all Kozak consensus information is written. '
'Only applicable if DNA reads are given.'))
<|code_end|>
with the help of current file imports:
import sys
import argparse
from os.path import basename
from Bio.Data.CodonTable import TranslationError
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
from dark.dna import findKozakConsensus
and context from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
, which may contain function names, class names, or code. Output only the next line. | addFASTACommandLineOptions(parser) |
Using the snippet: <|code_start|> '(as specified by --minORFLength) will be output as long as '
'they are open.'))
parser.add_argument(
'--minORFLength', metavar='LEN', type=int, default=None,
help='Only ORFs of at least this length will be written to stdout.')
parser.add_argument(
'--maxORFLength', metavar='LEN', type=int, default=None,
help=('Only ORFs of a maximum of this length will be written to '
'stdout.'))
parser.add_argument(
'--kozakOnly', default=False, action='store_true',
help=('Only ORFs that also have a Kozak consensus will be written to '
'stdout. Only applicable if DNA reads are given.'))
parser.add_argument(
'--kozakInfoFile',
help=('Filename to which all Kozak consensus information is written. '
'Only applicable if DNA reads are given.'))
addFASTACommandLineOptions(parser)
args = parser.parse_args()
allowOpenORFs = args.allowOpenORFs
minORFLength = args.minORFLength
maxORFLength = args.maxORFLength
kozakInfoFile = args.kozakInfoFile
kozakOnly = args.kozakOnly
<|code_end|>
, determine the next line of code. You have imports:
import sys
import argparse
from os.path import basename
from Bio.Data.CodonTable import TranslationError
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
from dark.dna import findKozakConsensus
and context (class names, function names, or code) available:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | reads = parseFASTACommandLineOptions(args) |
Using the snippet: <|code_start|> formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description=('Split sequences in a FASTA file into separate files, named '
'either by their sequence id or numerically.'))
parser.add_argument(
'--outDir', default='.',
help='The directory to make the files in.')
parser.add_argument(
'--verbose', default=False, action='store_true',
help='If given, print sequence ids as they are processed.')
parser.add_argument(
'--numeric', default=False, action='store_true',
help='If given, use numeric filenames, like 1.fasta, 2.fasta, etc.')
parser.add_argument(
'--noLeadingZeroes', default=False, action='store_true',
help='If given, numeric filenames will not have leading zeroes.')
parser.add_argument(
'--force', default=False, action='store_true',
help='If given, overwrite pre-existing files.')
parser.add_argument(
'--saveAs', choices=('fasta', 'fastq', 'fasta-ss'),
help=('The output format. The default is to match the input format, '
'so there is usually no need to specify this option. It can be '
'used to force conversion from FASTQ to FASTA'))
<|code_end|>
, determine the next line of code. You have imports:
import sys
import argparse
from os.path import join, exists
from os import mkdir, rename
from math import log10
from dark.reads import (addFASTACommandLineOptions,
parseFASTACommandLineOptions)
and context (class names, function names, or code) available:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | addFASTACommandLineOptions(parser) |
Based on the snippet: <|code_start|> 'either by their sequence id or numerically.'))
parser.add_argument(
'--outDir', default='.',
help='The directory to make the files in.')
parser.add_argument(
'--verbose', default=False, action='store_true',
help='If given, print sequence ids as they are processed.')
parser.add_argument(
'--numeric', default=False, action='store_true',
help='If given, use numeric filenames, like 1.fasta, 2.fasta, etc.')
parser.add_argument(
'--noLeadingZeroes', default=False, action='store_true',
help='If given, numeric filenames will not have leading zeroes.')
parser.add_argument(
'--force', default=False, action='store_true',
help='If given, overwrite pre-existing files.')
parser.add_argument(
'--saveAs', choices=('fasta', 'fastq', 'fasta-ss'),
help=('The output format. The default is to match the input format, '
'so there is usually no need to specify this option. It can be '
'used to force conversion from FASTQ to FASTA'))
addFASTACommandLineOptions(parser)
args = parser.parse_args()
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import argparse
from os.path import join, exists
from os import mkdir, rename
from math import log10
from dark.reads import (addFASTACommandLineOptions,
parseFASTACommandLineOptions)
and context (classes, functions, sometimes code) from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | reads = parseFASTACommandLineOptions(args) |
Given snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description=('Find sequences that have a specific property (as detected '
'by the "relabel" function in the file specified by '
'--relabelFunctionFile) and print a TAB-separated list of '
'renamings to standard output.'))
parser.add_argument(
'--relabelFunctionFile', required=True,
help=('A file containing a Python function named "relabel" that takes a '
'list of reads and returns a dictionary of renamings.'))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import argparse
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
and context:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
which might include code, classes, or functions. Output only the next line. | addFASTACommandLineOptions(parser) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description=('Find sequences that have a specific property (as detected '
'by the "relabel" function in the file specified by '
'--relabelFunctionFile) and print a TAB-separated list of '
'renamings to standard output.'))
parser.add_argument(
'--relabelFunctionFile', required=True,
help=('A file containing a Python function named "relabel" that takes a '
'list of reads and returns a dictionary of renamings.'))
addFASTACommandLineOptions(parser)
args = parser.parse_args()
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import argparse
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
and context (classes, functions, sometimes code) from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | reads = parseFASTACommandLineOptions(args) |
Using the snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=(
'Given FASTA on stdin, write the ids, sequences, and '
'quality strings on a single TAB-separated line to stdout.'))
parser.add_argument('--separator', default='\t',
help=('The character string to separate ids from '
'sequences and quality strings (if any)'))
parser.add_argument('--removeIds', default=False, action='store_true',
help='Do not print sequence ids')
<|code_end|>
, determine the next line of code. You have imports:
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
import argparse
and context (class names, function names, or code) available:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | addFASTACommandLineOptions(parser) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=(
'Given FASTA on stdin, write the ids, sequences, and '
'quality strings on a single TAB-separated line to stdout.'))
parser.add_argument('--separator', default='\t',
help=('The character string to separate ids from '
'sequences and quality strings (if any)'))
parser.add_argument('--removeIds', default=False, action='store_true',
help='Do not print sequence ids')
addFASTACommandLineOptions(parser)
args = parser.parse_args()
sep = args.separator
<|code_end|>
using the current file's imports:
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
import argparse
and any relevant context from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | reads = parseFASTACommandLineOptions(args) |
Next line prediction: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=('Given FASTA on stdin, write a summary of sequence base '
'categories to stdout. It is currently not possible to '
'specify the categories on the command line.'))
parser.add_argument(
'--baseType', default='nucl', choices=('nucl', 'prot'),
help='The type of the bases in the input.')
parser.add_argument(
'--minLength', default=1, type=int,
help=('If specified, stretches of reads that are less than this '
'length will not be reported but will be summarized by an '
'ellipsis.'))
parser.add_argument(
'--concise', action='store_true', default=False,
help='If specified, do not show the individual sequence regions.')
<|code_end|>
. Use current file imports:
(from collections import defaultdict
from math import log10
from dark.aa import NAMES
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
from dark.summarize import sequenceCategoryLengths
import argparse)
and context including class names, function names, or small code snippets from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | addFASTACommandLineOptions(parser) |
Using the snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=('Given FASTA on stdin, write a summary of sequence base '
'categories to stdout. It is currently not possible to '
'specify the categories on the command line.'))
parser.add_argument(
'--baseType', default='nucl', choices=('nucl', 'prot'),
help='The type of the bases in the input.')
parser.add_argument(
'--minLength', default=1, type=int,
help=('If specified, stretches of reads that are less than this '
'length will not be reported but will be summarized by an '
'ellipsis.'))
parser.add_argument(
'--concise', action='store_true', default=False,
help='If specified, do not show the individual sequence regions.')
addFASTACommandLineOptions(parser)
args = parser.parse_args()
<|code_end|>
, determine the next line of code. You have imports:
from collections import defaultdict
from math import log10
from dark.aa import NAMES
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
from dark.summarize import sequenceCategoryLengths
import argparse
and context (class names, function names, or code) available:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | reads = parseFASTACommandLineOptions(args) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
from __future__ import print_function, division
if __name__ == '__main__':
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description=('Given FASTA on stdin and a set of filtering criteria '
'write filtered FASTA to stdout.'))
parser.add_argument(
'--quiet', action='store_true', default=False,
help=('If True, do not print the final sequence summary.'))
parser.add_argument(
'--saveAs', choices=('fasta', 'fastq', 'fasta-ss'),
help=('The output format. The default is to match the input format, '
'so there is usually no need to specify this option. It can be '
'used to force conversion from FASTQ to FASTA'))
parser.add_argument(
'--checkResultCount', type=int,
help=('The number of reads expected in the output. If this number is '
'not seen, the script exits with status 1 and an error '
'message is printed unless --quiet was used.'))
<|code_end|>
, predict the next line using imports from the current file:
import sys
import argparse
from dark.filter import (
addFASTAFilteringCommandLineOptions, parseFASTAFilteringCommandLineOptions,
addFASTAEditingCommandLineOptions, parseFASTAEditingCommandLineOptions)
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
and context including class names, function names, and sometimes code from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | addFASTACommandLineOptions(parser) |
Predict the next line after this snippet: <|code_start|> 'write filtered FASTA to stdout.'))
parser.add_argument(
'--quiet', action='store_true', default=False,
help=('If True, do not print the final sequence summary.'))
parser.add_argument(
'--saveAs', choices=('fasta', 'fastq', 'fasta-ss'),
help=('The output format. The default is to match the input format, '
'so there is usually no need to specify this option. It can be '
'used to force conversion from FASTQ to FASTA'))
parser.add_argument(
'--checkResultCount', type=int,
help=('The number of reads expected in the output. If this number is '
'not seen, the script exits with status 1 and an error '
'message is printed unless --quiet was used.'))
addFASTACommandLineOptions(parser)
addFASTAFilteringCommandLineOptions(parser)
addFASTAEditingCommandLineOptions(parser)
args = parser.parse_args()
# Note that we must call parseFASTACommandLineOptions here before we
# examine args.fasta in the following code. That's because
# parseFASTACommandLineOptions sets args.fasta to be True if no format
# is given.
reads = parseFASTAEditingCommandLineOptions(
args, parseFASTAFilteringCommandLineOptions(
<|code_end|>
using the current file's imports:
import sys
import argparse
from dark.filter import (
addFASTAFilteringCommandLineOptions, parseFASTAFilteringCommandLineOptions,
addFASTAEditingCommandLineOptions, parseFASTAEditingCommandLineOptions)
from dark.reads import addFASTACommandLineOptions, parseFASTACommandLineOptions
and any relevant context from other files:
# Path: dark/reads.py
# def addFASTACommandLineOptions(parser):
# """
# Add standard command-line options to an argparse parser.
#
# @param parser: An C{argparse.ArgumentParser} instance.
# """
#
# parser.add_argument(
# '--fastaFile', type=open, default=sys.stdin, metavar='FILENAME',
# help=('The name of the FASTA input file. Standard input will be read '
# 'if no file name is given.'))
#
# parser.add_argument(
# '--readClass', default='DNARead', choices=readClassNameToClass,
# metavar='CLASSNAME',
# help=('If specified, give the type of the reads in the input. '
# 'Possible choices: %s.' % ', '.join(readClassNameToClass)))
#
# # A mutually exclusive group for either --fasta, --fastq, or --fasta-ss
# group = parser.add_mutually_exclusive_group()
#
# group.add_argument(
# '--fasta', default=False, action='store_true',
# help=('If specified, input will be treated as FASTA. This is the '
# 'default.'))
#
# group.add_argument(
# '--fastq', default=False, action='store_true',
# help='If specified, input will be treated as FASTQ.')
#
# group.add_argument(
# '--fasta-ss', dest='fasta_ss', default=False, action='store_true',
# help=('If specified, input will be treated as PDB FASTA '
# '(i.e., regular FASTA with each sequence followed by its '
# 'structure).'))
#
# def parseFASTACommandLineOptions(args):
# """
# Examine parsed command-line options and return a Reads instance.
#
# @param args: An argparse namespace, as returned by the argparse
# C{parse_args} function.
# @return: A C{Reads} subclass instance, depending on the type of FASTA file
# given.
# """
# # Set default FASTA type.
# if not (args.fasta or args.fastq or args.fasta_ss):
# args.fasta = True
#
# readClass = readClassNameToClass[args.readClass]
#
# if args.fasta:
# from dark.fasta import FastaReads
# return FastaReads(args.fastaFile, readClass=readClass)
# elif args.fastq:
# from dark.fastq import FastqReads
# return FastqReads(args.fastaFile, readClass=readClass)
# else:
# from dark.fasta_ss import SSFastaReads
# return SSFastaReads(args.fastaFile, readClass=readClass)
. Output only the next line. | args, parseFASTACommandLineOptions(args))) |
Based on the snippet: <|code_start|>
class TestConstants(TestCase):
"""
Test constants in dark.cigar
"""
def testOperations(self):
"""
Make sure the CIGAR operation strings have the expected one-letter
codes.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import TestCase
from pysam import CSOFT_CLIP, CHARD_CLIP, CMATCH, CINS
from dark.cigar import (
CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
dna2cigar, makeCigar, cigarTuplesToOperations, softClippedOffset,
insertionOffset)
and context (classes, functions, sometimes code) from other files:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
. Output only the next line. | self.assertEqual('I', CINS_STR) |
Predict the next line for this snippet: <|code_start|>
class TestConstants(TestCase):
"""
Test constants in dark.cigar
"""
def testOperations(self):
"""
Make sure the CIGAR operation strings have the expected one-letter
codes.
"""
self.assertEqual('I', CINS_STR)
<|code_end|>
with the help of current file imports:
from unittest import TestCase
from pysam import CSOFT_CLIP, CHARD_CLIP, CMATCH, CINS
from dark.cigar import (
CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
dna2cigar, makeCigar, cigarTuplesToOperations, softClippedOffset,
insertionOffset)
and context from other files:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual('D', CDEL_STR) |
Given the following code snippet before the placeholder: <|code_start|>
class TestConstants(TestCase):
"""
Test constants in dark.cigar
"""
def testOperations(self):
"""
Make sure the CIGAR operation strings have the expected one-letter
codes.
"""
self.assertEqual('I', CINS_STR)
self.assertEqual('D', CDEL_STR)
<|code_end|>
, predict the next line using imports from the current file:
from unittest import TestCase
from pysam import CSOFT_CLIP, CHARD_CLIP, CMATCH, CINS
from dark.cigar import (
CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
dna2cigar, makeCigar, cigarTuplesToOperations, softClippedOffset,
insertionOffset)
and context including class names, function names, and sometimes code from other files:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
. Output only the next line. | self.assertEqual('M', CMATCH_STR) |
Using the snippet: <|code_start|>
class TestConstants(TestCase):
"""
Test constants in dark.cigar
"""
def testOperations(self):
"""
Make sure the CIGAR operation strings have the expected one-letter
codes.
"""
self.assertEqual('I', CINS_STR)
self.assertEqual('D', CDEL_STR)
self.assertEqual('M', CMATCH_STR)
<|code_end|>
, determine the next line of code. You have imports:
from unittest import TestCase
from pysam import CSOFT_CLIP, CHARD_CLIP, CMATCH, CINS
from dark.cigar import (
CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
dna2cigar, makeCigar, cigarTuplesToOperations, softClippedOffset,
insertionOffset)
and context (class names, function names, or code) available:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
. Output only the next line. | self.assertEqual('=', CEQUAL_STR) |
Given snippet: <|code_start|>
class TestConstants(TestCase):
"""
Test constants in dark.cigar
"""
def testOperations(self):
"""
Make sure the CIGAR operation strings have the expected one-letter
codes.
"""
self.assertEqual('I', CINS_STR)
self.assertEqual('D', CDEL_STR)
self.assertEqual('M', CMATCH_STR)
self.assertEqual('=', CEQUAL_STR)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest import TestCase
from pysam import CSOFT_CLIP, CHARD_CLIP, CMATCH, CINS
from dark.cigar import (
CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
dna2cigar, makeCigar, cigarTuplesToOperations, softClippedOffset,
insertionOffset)
and context:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
which might include code, classes, or functions. Output only the next line. | self.assertEqual('X', CDIFF_STR) |
Continue the code snippet: <|code_start|>
class TestConstants(TestCase):
"""
Test constants in dark.cigar
"""
def testOperations(self):
"""
Make sure the CIGAR operation strings have the expected one-letter
codes.
"""
self.assertEqual('I', CINS_STR)
self.assertEqual('D', CDEL_STR)
self.assertEqual('M', CMATCH_STR)
self.assertEqual('=', CEQUAL_STR)
self.assertEqual('X', CDIFF_STR)
class TestDNA2CIGAR(TestCase):
"""
Test the dna2cigar function.
"""
def testUnequalStrings(self):
"""
If two unequal strings are passed, a ValueError must be raised.
"""
error = r"^Sequences 'hey' and 'there' of unequal length \(3 != 5\)\.$"
<|code_end|>
. Use current file imports:
from unittest import TestCase
from pysam import CSOFT_CLIP, CHARD_CLIP, CMATCH, CINS
from dark.cigar import (
CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
dna2cigar, makeCigar, cigarTuplesToOperations, softClippedOffset,
insertionOffset)
and context (classes, functions, or code) from other files:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
. Output only the next line. | self.assertRaisesRegex(ValueError, error, dna2cigar, 'hey', 'there') |
Given snippet: <|code_start|> self.assertEqual('2M', dna2cigar('GA', 'TA', concise=True))
def testMixedMatch(self):
"""
If two strings with matching and non-matching regions must result
in the expected CIGAR string.
"""
self.assertEqual('3=4X5=2X',
dna2cigar('ACGTTTTCCCTTGG',
'ACGAAAACCCTTTT'))
def testMixedMatchConcise(self):
"""
If two strings with matching and non-matching regions must result
in the expected CIGAR string when the concise argument is True.
"""
self.assertEqual('14M',
dna2cigar('ACGTTTTCCCTTGG',
'ACGAAAACCCTTTT', concise=True))
class TestMakeCigar(TestCase):
"""
Test making CIGAR strings.
"""
def testEmptyReference(self):
"""
If the reference is empty, a ValueError must be raised.
"""
error = r"^Empty reference$"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest import TestCase
from pysam import CSOFT_CLIP, CHARD_CLIP, CMATCH, CINS
from dark.cigar import (
CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
dna2cigar, makeCigar, cigarTuplesToOperations, softClippedOffset,
insertionOffset)
and context:
# Path: dark/cigar.py
# (CINS_STR, CDEL_STR, CMATCH_STR, CEQUAL_STR, CDIFF_STR,
# CHARD_CLIP_STR) = 'IDM=XH'
# def dna2cigar(s1, s2, concise=False):
# def makeCigar(reference, query, noEdgeInsertions=True):
# def cigarTuplesToOperations(tuples, includeHardClip=True):
# def softClippedOffset(offset, pairs, cigarOperations):
# def insertionOffset(offset, pairs, cigarOperations):
which might include code, classes, or functions. Output only the next line. | self.assertRaisesRegex(ValueError, error, makeCigar, '', 'ACGT') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.