code stringlengths 101 5.91M |
|---|
class PrefetchDataset(torch.utils.data.Dataset):
def __init__(self, opt, dataset, pre_process_func):
self.images = dataset.images
self.load_image_func = dataset.coco.loadImgs
self.img_dir = dataset.img_dir
self.pre_process_func = pre_process_func
self.opt = opt
def __geti... |
def distribute_position_amplitude_data(data: PositionAmplitudeData) -> PositionAmplitudeData:
walker_data = data['walker_data']
move_metadata = data['move_metadata']
walker_data = default_distribute_data(walker_data)
move_metadata = replicate_all_local_devices(move_metadata)
return PositionAmplitude... |
def split_needed(next_el, current_types, last_type):
repeatable_if_adjacent = {'REPORTNUMBER', 'COLLABORATION'}
next_type = ('ARXIV' if next_el.get('is_arxiv') else next_el['type'])
if (';' in next_el['misc_txt']):
return 'semicolon'
if ((next_type in (current_types - repeatable_if_adjacent)) or... |
class QNLI(AbstractTask):
name = 'qnli'
labels_list = ['0', '1']
metric = [metrics.accuracy]
metric_names = ['accuracy']
split_to_data_split = {'train': 'train', 'validation': 'validation', 'test': 'validation'}
def load_dataset(self, split):
return datasets.load_dataset('glue', 'qnli', ... |
def get_transformer_hidden_size(model: transformers.PreTrainedModel):
if isinstance(model, transformers.GPT2LMHeadModel):
hidden_size_attr_name = 'n_embd'
elif isinstance(model, transformers.OPTForCausalLM):
hidden_size_attr_name = 'word_embed_proj_dim'
elif isinstance(model, transformers.T5... |
_model
def tf_efficientnet_b0_ap(pretrained=False, **kwargs):
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet('tf_efficientnet_b0_ap', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)
return model |
class SyntacticMetric(Metric):
def __init__(self):
pass
def evaluate_example(self, summary, reference):
with CoreNLPClient(annotators=['tokenize', 'ssplit', 'pos', 'lemma', 'parse'], timeout=30000, memory='16G') as client:
answer = get_stats(client, summary)
return answer... |
def to_tensor_slice_dataset(data, label, config):
features = collections.OrderedDict()
output_types = collections.OrderedDict()
for i in range(len(CONTINUOUS_COLUMNS)):
import numpy as np
features[CONTINUOUS_COLUMNS[i]] = data[i].astype(np.float32)
output_types[CONTINUOUS_COLUMNS[i]]... |
class AgentGenerator():
def __init__(self, args):
self.client = carla.Client(args.host, args.port)
self.client.set_timeout(10.0)
self.world = self.client.get_world()
self.map = self.world.get_map()
self.tm = self.client.get_trafficmanager(args.tm_port)
self.tm.set_glo... |
_criterion('wav2vec', dataclass=Wav2VecCriterionConfig)
class Wav2vecCriterion(FairseqCriterion):
def __init__(self, task, infonce=False, loss_weights=None, log_keys=None):
super().__init__(task)
self.infonce = infonce
self.loss_weights = loss_weights
self.log_keys = ([] if (log_keys... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
(model_args, data_args, training_args) = parser.parse_args_into_dataclasses()
if ((data_args.eval_data_file is None) and training_args.do_eval):
raise ValueError('Cannot do evaluation without an evaluat... |
class VectorType(LaVarType):
def __init__(self, rows=0, desc=None, element_type=ScalarType(), symbol=None, dynamic=DynamicTypeEnum.DYN_INVALID, rows_ir=None):
LaVarType.__init__(self, VarTypeEnum.VECTOR, desc, element_type, symbol, dynamic=dynamic)
self.rows = rows
self.rows_ir = rows_ir
... |
class FlipTensor(nn.Module):
def __init__(self, dim=(- 2), item_index=None):
super(FlipTensor, self).__init__()
self.dim = dim
self.item_index = item_index
def flip(self, x):
if (self.dim is not None):
if (self.item_index is None):
return x.flip(dims=[... |
def interpolate(dist, length, mode, max_curvature, origin_x, origin_y, origin_yaw):
if (mode == 'S'):
x = (origin_x + ((dist / max_curvature) * math.cos(origin_yaw)))
y = (origin_y + ((dist / max_curvature) * math.sin(origin_yaw)))
yaw = origin_yaw
else:
ldx = (math.sin(dist) / m... |
def cycle(dataloader, distributed=False):
epoch = 0
while True:
for (images, targets) in dataloader:
(yield (images, targets))
epoch += 1
if distributed:
dataloader.sampler.set_epoch(epoch) |
def plot(deephyperedges_directory, MLP_directory, deepsets_directory, metric, dataset):
dhe_metrics = pd.read_csv(deephyperedges_directory)
x = []
y = []
for (index, row) in dhe_metrics.iterrows():
x.append(float(row['Step']))
y.append(float(row['Value']))
mlp_metrics = pd.read_csv(M... |
def test_boradcast_data(model_parallel_size):
if (torch.distributed.get_rank() == 0):
print('> testing boradcast_data with model parallel size {} ...'.format(model_parallel_size))
mpu.initialize_model_parallel(model_parallel_size)
torch.manual_seed((1234 + mpu.get_data_parallel_rank()))
model_pa... |
def test_corpus_czech(recwarn):
s = pd.Series(['Holka modrooka nesedavej tam', 'Holka modrooka nesedavej u potoka', 'podemele tvoje oci', 'vezme li te bude skoda', 'V potoce je hastrmanek', 'V potoce je velka voda', 'V potoce se voda toci', 'zataha te za copanek'])
corpus = tn.Corpus(s, lang='cs')
assert (l... |
def attention(q, k, v, d_k, mask=None, dropout=None):
scores = (torch.matmul(q, k.transpose((- 2), (- 1))) / math.sqrt(d_k))
if (mask is not None):
mask = mask.unsqueeze(1)
scores = scores.masked_fill((mask == 0), (- .0))
scores = F.softmax(scores, dim=(- 1))
if (dropout is not None):
... |
class BidirectionalLSTM(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(BidirectionalLSTM, self).__init__()
self.rnn = nn.LSTM(input_size, hidden_size, bidirectional=True, batch_first=True)
self.linear = nn.Linear((hidden_size * 2), output_size)
def forward(se... |
def show_doc_from_name(mod_name, ft_name: str, doc_string: bool=True, arg_comments: dict={}, alt_doc_string: str=''):
mod = import_mod(mod_name)
splits = str.split(ft_name, '.')
assert hasattr(mod, splits[0]), print(f"Module {mod_name} doesn't have a function named {splits[0]}.")
elt = getattr(mod, spli... |
class RealmConfig(PretrainedConfig):
model_type = 'realm'
def __init__(self, vocab_size=30522, hidden_size=768, retriever_proj_size=128, num_hidden_layers=12, num_attention_heads=12, num_candidates=8, intermediate_size=3072, hidden_act='gelu_new', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_p... |
class StyleGAN2Discriminator(nn.Module):
def __init__(self, resolution, image_channels=3, label_size=0, architecture='resnet', use_wscale=True, minibatch_std_group_size=4, minibatch_std_channels=1, fmaps_base=(32 << 10), fmaps_max=512):
super().__init__()
if (resolution not in _RESOLUTIONS_ALLOWED):... |
def init_quantize_config(model, quantize_recipe=None):
assert ('quantize_config' not in global_config), 'quantize_config has been unexpectedly created. Please check your QAT workflow'
config = QuantizeConfig()
config_quantizable_layers(model)
if quantize_recipe:
config.add_quantize_recipe(quanti... |
_register
class Pruner():
def __init__(self, start_epoch=None, end_epoch=None, initial_sparsity=None, target_sparsity=None, update_frequency=1, method='per_tensor', prune_type='basic_magnitude', start_step=None, end_step=None, update_frequency_on_step=None, prune_domain=None, sparsity_decay_type=None, pattern='tile... |
def randreg_equation(n, reg, d_min=2, d_max=3, seed=None):
import networkx as nx
G = nx.random_regular_graph(reg, n, seed=seed)
inputs = [[] for _ in range(n)]
for (i, (na, nb)) in enumerate(G.edges):
ix = get_symbol(i)
inputs[na].append(ix)
inputs[nb].append(ix)
rng = random... |
class STP_Base_Net(torch.nn.Module):
def __init__(self, args):
super(STP_Base_Net, self).__init__()
self.args = args
self.ip_emb = torch.nn.Linear(2, self.args['input_embedding_size'])
self.enc_rnn = torch.nn.GRU(self.args['input_embedding_size'], self.args['encoder_size'], 1, batch_... |
class BaseOptions():
def __init__(self):
self.initialized = False
def initialize(self, parser):
parser.add_argument('--name', type=str, default='label2coco', help='name of the experiment. It decides where to store samples and models')
parser.add_argument('--gpu_ids', type=str, default='0... |
def parse_args():
parser = argparse.ArgumentParser(description='Go LT-NCF')
parser.add_argument('--bpr_batch', type=int, default=2048, help='the batch size for bpr loss training procedure')
parser.add_argument('--recdim', type=int, default=64, help='the embedding size of LT-NCF')
parser.add_argument('--... |
def _check_is_aligned(df, id_col, dt_col):
res = (len(set(df.groupby(id_col).apply((lambda df: hash(str(df[dt_col].values)))))) == 1)
return res |
class MLP_G(nn.Module):
def __init__(self, ninput, noutput, layers, activation=nn.ReLU(), gpu=True):
super(MLP_G, self).__init__()
self.ninput = ninput
self.noutput = noutput
layer_sizes = ([ninput] + [int(x) for x in layers.split('-')])
self.layers = []
for i in rang... |
def get_time_gap(s, e):
return (datetime.datetime.fromtimestamp(e) - datetime.datetime.fromtimestamp(s)).__str__() |
def test_pointers(msg):
living_before = ConstructorStats.get(UserType).alive()
assert (m.get_void_ptr_value(m.return_void_ptr()) == 4660)
assert m.get_void_ptr_value(UserType())
assert (ConstructorStats.get(UserType).alive() == living_before)
with pytest.raises(TypeError) as excinfo:
m.get_v... |
class Product(MergeOperator):
def __call__(self, base_encoding, side_encoding, additional_encodings=[]):
merged_encoding = (base_encoding * side_encoding)
for add_encoding in additional_encodings:
merged_encoding *= add_encoding
return merged_encoding |
class TrainEpocher(Epocher):
def __init__(self, *, model: Union[(Model, nn.Module)], optimizer: T_optim, labeled_loader: T_loader, unlabeled_loader: T_loader, sup_criterion: T_loss, num_batches: int, cur_epoch=0, device='cpu', train_with_two_stage: bool=False, disable_bn_track_for_unlabeled_data: bool=False, **kwar... |
def register_cdod_pascal_voc(name, dirname, split, year, class_names):
DatasetCatalog.register(name, (lambda : load_cdod_voc_instances(dirname, split, class_names)))
MetadataCatalog.get(name).set(thing_classes=list(class_names), dirname=dirname, year=year, split=split) |
class RepVGGOur(nn.Module):
expansion: int = 1
def __init__(self, inplanes, planes, stride=1, groups=1, kernel_size=3, se_block=True, additional_branches=[]):
super().__init__()
activation = nn.ReLU()
if ('swish' in additional_branches):
activation = nn.SiLU()
self.bl... |
class CustomSACPolicy(SACPolicy):
def __init__(self, *args, **kwargs):
super(CustomSACPolicy, self).__init__(*args, **kwargs, layers=[256, 256], feature_extraction='mlp') |
def make_args_list(n_trials_from, n_trials, dataset_names, algorithms, n_hparams_from, n_hparams, steps, data_dir, task, holdout_fraction, single_test_envs, hparams):
args_list = []
for trial_seed in range(n_trials_from, (n_trials_from + n_trials)):
for dataset in dataset_names:
for algorith... |
def _reset_library_root_logger() -> None:
global _default_handler
with _lock:
if (not _default_handler):
return
library_root_logger = _get_library_root_logger()
library_root_logger.removeHandler(_default_handler)
library_root_logger.setLevel(logging.NOTSET)
_d... |
def convert_model(model, args):
for m in model._modules:
child = model._modules[m]
if is_pruned(child):
if (get_layer_info(child) in ['LGC']):
model._modules[m] = CondensingLGC(child)
elif (get_layer_info(child) in ['SFR']):
model._modules[m] =... |
class YolosModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class PredictionLossGame(CooperativeGame):
def __init__(self, extension, sample, label, loss, groups=None):
if (sample.ndim == 1):
sample = sample[np.newaxis]
if np.isscalar(label):
label = np.array([label])
if (loss is utils.crossentropyloss):
if ((label.... |
def write_sentences(write_path, premises, hypotheses, append=False):
print('Writing to {}\n'.format(write_path))
if append:
with open(write_path, 'a') as f:
for p in premises:
f.write(p)
f.write('\n')
for h in hypotheses:
f.write(h)... |
def InceptionV3(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000, **kwargs):
global backend, layers, models, keras_utils
(backend, layers, models, keras_utils) = get_submodules_from_kwargs(kwargs)
if (not ((weights in {'imagenet', None}) or os.path.exists... |
class WarmUp(tf.keras.optimizers.schedules.LearningRateSchedule):
def __init__(self, initial_learning_rate: float, decay_schedule_fn: Callable, warmup_steps: int, power: float=1.0, name: str=None):
super().__init__()
self.initial_learning_rate = initial_learning_rate
self.warmup_steps = warm... |
class ContextBlock(nn.Module):
def __init__(self, inplanes, ratio, pooling_type='att', fusion_types=('channel_add',)):
super(ContextBlock, self).__init__()
assert (pooling_type in ['avg', 'att'])
assert isinstance(fusion_types, (list, tuple))
valid_fusion_types = ['channel_add', 'cha... |
class PlasmaArray():
def __init__(self, array):
super().__init__()
self.array = array
self.disable = (array.nbytes < )
self.object_id = None
self.path = None
self._client = None
self._server = None
self._server_tmp = None
self._plasma = None
... |
class DebertaV2ForMaskedLM(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def getPathGS(algo, inputEvents, tthread, NUM_ITEMS, NUM_ACCESS, key_skewness, overlap_ratio, abort_ratio, isCyclic, complexity):
return (FILE_FOLER + '/GrepSum/{}/threads = {}/totalEvents = {}/{}_{}_{}_{}_{}_{}_{}.latency'.format(algo, tthread, inputEvents, NUM_ITEMS, NUM_ACCESS, key_skewness, overlap_ratio, abort... |
class Precision_grt():
def __init__(self, length=20, threshold=5):
self.length = length
self.threshold = threshold
def init(self, train):
return
def reset(self):
self.test = 0
self.hit = 0
def add(self, result, next_item, for_item=0, session=0, pop_bin=None, posit... |
def min_gt(seq: np.ndarray, val: Any) -> Any:
min = np.inf
idx = (len(seq) - 1)
while (idx >= 0):
if ((seq[idx] >= val) and (seq[idx] < min)):
min = seq[idx]
idx -= 1
return min |
def C2D_Axial_ResNet50(**kwargs):
c3d_idx = [[], [], [], []]
nl_idx = [[], [], [], []]
sa_idx = [[], [2, 3], [3, 4, 5], []]
return ResNet503D(AP3D.APP3DC, c3d_idx, nl_idx, sa_idx, **kwargs) |
def main_worker(gpu, ngpus_per_node, args):
global best_mIoU
args.gpu = gpu
if (args.gpu is not None):
print('Use GPU: {} for training'.format(args.gpu))
if args.distributed:
if ((args.dist_url == 'env://') and (args.rank == (- 1))):
args.rank = int(os.environ['RANK'])
... |
def flatten(l):
for el in l:
if hasattr(el, '__iter__'):
for sub in flatten(el):
(yield sub)
else:
(yield el) |
def _building_block_v1(inputs, filters, training, projection_shortcut, strides, data_format, bn):
shortcut = inputs
if (projection_shortcut is not None):
shortcut = projection_shortcut(inputs)
if bn:
shortcut = batch_norm(inputs=shortcut, training=training, data_format=data_format)
... |
def _test_build_detectors(self, device):
cfg_files = get_config_files(None, EXCLUDED_FOLDERS)
self.assertGreater(len(cfg_files), 0)
for cfg_file in cfg_files:
with self.subTest(cfg_file=cfg_file):
print('Testing {}...'.format(cfg_file))
cfg = utils.load_config_from_file(cfg_f... |
def get_encoding_dict(sentence_to_labels, original_file_path, aug_type, alpha):
encodings_path = get_encodings_path(original_file_path, aug_type, alpha)
if (not encodings_path.exists()):
print(f'creating {encodings_path}')
string_to_encoding = {}
for sentence in tqdm(sentence_to_labels.k... |
class TestLLaVA(unittest.TestCase):
def setUpClass(self):
self.model = LlavaMistralForCausalLM.from_pretrained(MODEL_NAME, low_cpu_mem_usage=True)
self.tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
self.dummpy_input = {'input_ids': torch.tensor([[1, 1, 2, 2]]), 'labels': torch.tensor... |
def load_data(data_dir, batch_size, dev_ratio, device):
(train_docs, test_docs, vocab) = read_dataset(data_dir)
if (dev_ratio > 0):
print('splitting train, dev datasets')
(train_docs, dev_docs) = train_test_split(train_docs, test_size=dev_ratio, shuffle=True)
print('train, dev, test', le... |
def find_coref(ment, mentlist, person_names):
cur_m = ment['mention'].lower()
coref = []
for m in mentlist:
if ((len(m['candidates']) == 0) or (m['candidates'][0][0] not in person_names)):
continue
mention = m['mention'].lower()
start_pos = mention.find(cur_m)
if ... |
class HandEggTouchSensorsEnv(ManipulateTouchSensorsEnv):
def __init__(self, target_position='random', target_rotation='xyz', reward_type='sparse'):
super(HandEggTouchSensorsEnv, self).__init__(model_path=MANIPULATE_EGG_XML, target_position=target_position, target_rotation=target_rotation, target_position_ra... |
class ElectraModelTester():
def __init__(self, parent):
self.parent = parent
self.batch_size = 13
self.seq_length = 7
self.is_training = True
self.use_input_mask = True
self.use_token_type_ids = True
self.use_labels = True
self.vocab_size = 99
... |
def apply_sequential(inputs, modules):
for mod in modules:
if isinstance(mod, (nn.BatchNorm2d, nn.SyncBatchNorm)):
shapes = [i.shape for i in inputs]
spatial_sizes = [(s[2] * s[3]) for s in shapes]
x = [i.flatten(2) for i in inputs]
x = torch.cat(x, dim=2).uns... |
def masked_whiten(values, mask, shift_mean=True):
(mean, var) = (masked_mean(values, mask), masked_var(values, mask))
whitened = ((values - mean) * torch.rsqrt((var + 1e-08)))
if (not shift_mean):
whitened += mean
return whitened |
def _find_library_candidates(library_names, library_file_extensions, library_search_paths):
candidates = set()
for library_name in library_names:
for search_path in library_search_paths:
glob_query = os.path.join(search_path, (('*' + library_name) + '*'))
for filename in glob.igl... |
def _make_fusion_block(features, use_bn):
return FeatureFusionBlock_custom(features, nn.ReLU(False), deconv=False, bn=use_bn, expand=False, align_corners=True) |
def get_onnx_model():
import torch
import torchvision
from torch.autograd import Variable
model = torchvision.models.resnet18()
x = Variable(torch.randn(1, 3, 224, 224))
torch_out = torch.onnx.export(model, x, 'resnet18.onnx', export_params=True, verbose=True) |
def allreduce_grads(params, coalesce=True, bucket_size_mb=(- 1)):
warnings.warning('"mmcv.runner.fp16_utils.allreduce_grads" is deprecated, and will be removed in v2.8. Please switch to "mmcv.runner.allreduce_grads')
_allreduce_grads(params, coalesce=coalesce, bucket_size_mb=bucket_size_mb) |
def test_interpolation_potential_verticalfreq_outsidegrid():
rzpot = potential.interpRZPotential(RZPot=potential.MWPotential, rgrid=(0.01, 2.0, 201), logR=False, interpverticalfreq=True, zsym=False)
rs = [0.005, 2.5]
for r in rs:
vfdiff = numpy.fabs(((rzpot.verticalfreq(r) - potential.verticalfreq(p... |
class BatchNorm3d(_SyncBatchNorm):
def _check_input_dim(self, input):
if (input.dim() != 5):
raise ValueError('expected 5D input (got {}D input)'.format(input.dim()))
super(BatchNorm3d, self)._check_input_dim(input) |
def latest_checkpoint(checkpoint_dir, latest_filename=None):
ckpt_manager = CheckpointStateManager(checkpoint_dir, latest_filename=latest_filename)
return ckpt_manager.latest_checkpoint |
def _build_faster_rcnn_feature_extractor(feature_extractor_config, is_training, reuse_weights=None):
feature_type = feature_extractor_config.type
first_stage_features_stride = feature_extractor_config.first_stage_features_stride
if (feature_type not in FASTER_RCNN_FEATURE_EXTRACTOR_CLASS_MAP):
raise... |
def get_dist_info():
if (TORCH_VERSION < '1.0'):
initialized = dist._initialized
elif dist.is_available():
initialized = dist.is_initialized()
else:
initialized = False
if initialized:
rank = dist.get_rank()
world_size = dist.get_world_size()
else:
ran... |
def validation(args, model, device, train_loader, train_scp, train_utt2label, val_loader, val_scp, val_utt2label):
logger.info('Starting Validation')
(train_loss, train_scores) = compute_loss(model, device, train_loader)
(val_loss, val_scores) = compute_loss(model, device, val_loader)
(train_preds, trai... |
class UNet2DModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['torch'])
def from_pretrained(cls, *args, **kwargs):
requires_backends(cls, ['tor... |
(scope='session')
def saliency_gpt2_model_tiny():
return load_model('hf-internal-testing/tiny-random-GPT2LMHeadModel', 'saliency') |
def INTERN_B():
pretrained = None
print('use InternImage_B as backbone')
model = InternImage(_delete_=True, type='InternImage', core_op='DCNv3', channels=112, depths=[4, 4, 21, 4], groups=[7, 14, 28, 56], mlp_ratio=4.0, drop_path_rate=0.4, norm_layer='LN', layer_scale=1.0, offset_scale=1.0, post_norm=True, ... |
def write_info_file(info, model_base_filepath, cnt):
info_filename = (model_base_filepath + ('_%010d_info.txt' % cnt))
info_f = open(info_filename, 'w')
for (key, val) in info.items():
info_f.write(('%s=%s\n' % (key, val)))
info_f.close() |
def count_params(layer, **tags):
params = get_all_params(layer, **tags)
shapes = [p.get_value().shape for p in params]
counts = [np.prod(shape) for shape in shapes]
return sum(counts) |
def ant():
locals().update(default())
env = 'Ant-v1'
max_length = 1000
steps = .0
return locals() |
def get_duplicated_ugly_ts_df():
data = np.random.random_sample((50, 5))
df = pd.DataFrame(data, columns=['a', 'b', 'c', 'd', 'e'])
df['a'][0] = np.nan
df['datetime'] = pd.date_range('1/1/2019', periods=50)
for i in range(20):
df.loc[len(df)] = df.loc[np.random.randint(0, 49)]
return df |
def parse_args():
parser = argparse.ArgumentParser(description='deblur arguments')
parser.add_argument('--phase', type=str, default='test', help='determine whether train or test')
parser.add_argument('--datalist', type=str, default='./datalist_gopro.txt', help='training datalist')
parser.add_argument('-... |
class BasicUnitConverter(units.ConversionInterface):
def axisinfo(unit, axis):
if (unit == radians):
return units.AxisInfo(majloc=ticker.MultipleLocator(base=(np.pi / 2)), majfmt=ticker.FuncFormatter(rad_fn), label=unit.fullname)
elif (unit == degrees):
return units.AxisInfo(... |
class RewardFn(abc.ABC):
def __call__(self, state: State, action: chex.Array, next_state: State) -> chex.Array: |
class EnvSampler():
def __init__(self, env, max_path_length=1000):
self.env = env
self.path_length = 0
self.current_state = None
self.max_path_length = max_path_length
self.path_rewards = []
self.sum_reward = 0
def sample(self, agent, eval_t=False):
if (se... |
def load_merge_bracket(fname, path):
merge_file = (fname + '.story.doc.conll.merge')
brack_file = (fname + '.story.doc.conll.brackets')
(disco_seg, EDU_pool, EDU_nsubj) = read_discourse_merge(os.path.join(path, merge_file))
(link, dep) = new_read_bracket(os.path.join(path, brack_file), EDU_pool, EDU_nsu... |
def main(args):
corpus_files = os.listdir(args.tilde_corpus_dir)
corpus_dic = {}
for file in corpus_files:
with open((args.tilde_corpus_dir + f'/{file}'), 'r') as f:
lines = f.readlines()
for line in tqdm(lines, desc='Loading collection'):
data = json.loads(li... |
class _deconv2d(prettytensor.VarStoreMethod):
def __call__(self, input_layer, kernel, depth, name, stride, activation_fn, l2loss, init, stddev, bias, edges, batch_normalize):
if (len(input_layer.shape) != 4):
raise ValueError(('Cannot perform conv2d on tensor with shape %s' % input_layer.shape))... |
def test_digits_naive():
model = FeatureBasedSelection(100, 'sqrt', optimizer='naive')
model.fit(X_digits, sample_cost=X_digits_costs)
assert_array_equal(model.ranking, digits_ranking)
assert_array_almost_equal(model.gains, digits_gains, 4)
assert_less_equal(sum(X_digits_costs[model.ranking]), 100) |
def publish_others():
box = ((0., (- 0.), (- 0.)), Pose)
squeeze_area = (0., 0., (- 0.))
trash = (0., 0., (- 0.)) |
class TestWeightTying(unittest.TestCase):
def setUp(self):
self.seed = 42
vocab_size = 30
tokens = [f'tok{i:02d}' for i in range(vocab_size)]
self.vocab = Vocabulary(tokens=tokens)
self.cfg = {'model': {'tied_embeddings': False, 'tied_softmax': False, 'encoder': {'type': 'rec... |
def is_pretrained_cfg(model: str, tag: str):
if (model not in _PRETRAINED):
return False
return (tag.lower() in _PRETRAINED[model]) |
def md5_hash(path):
with open(path, 'rb') as f:
content = f.read()
return hashlib.md5(content).hexdigest() |
def build_neck(cfg):
assert (cfg.MODEL.NECK.CONV_BODY in registry.NECKS), 'cfg.MODEL.NECK.CONV_BODY: {} is not registered in registry'.format(cfg.MODEL.NECK.CONV_BODY)
return registry.NECKS[cfg.MODEL.NECK.CONV_BODY](cfg) |
def preprocess(args):
import spacy
global _NLP
_NLP = spacy.load('en', parser=False)
process_file(args.raw_devset_file, args.devset_file, args.n_history)
process_file(args.raw_trainset_file, args.trainset_file, args.n_history) |
class SLTopicDetectionConfig(FairseqDataclass):
data: str = field(default=MISSING, metadata={'help': 'path to data directory'})
dict_path: str = field(default=MISSING, metadata={'help': 'Path to dictionary mapping category number to category name'})
modeling_task: str = field(default='classification', metad... |
def test_tinydb_reader_loads_db_and_fs(tmpdir):
root = tmpdir.strpath
tinydb_obs = run_test_experiment(exp_name='exp1', exp_id='1234', root_dir=root)
tinydb_reader = TinyDbReader(root)
assert (tinydb_obs.fs.root == tinydb_reader.fs.root)
assert (str(tinydb_obs.runs.all()[0]) == str(tinydb_reader.run... |
def grid() -> chex.Array:
grid = jnp.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 1, 1, 0, 0, 1, 0, 0, 0], [0, 1, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0... |
def get_config():
config = ml_collections.ConfigDict()
config.algo = 'drq'
config.actor_lr = 0.0003
config.critic_lr = 0.0003
config.temp_lr = 0.0003
config.hidden_dims = (256, 256)
config.cnn_features = (32, 32, 32, 32)
config.cnn_strides = (2, 1, 1, 1)
config.cnn_padding = 'VALID'
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.