code stringlengths 101 5.91M |
|---|
def register_Ns3Channel_methods(root_module, cls):
cls.add_constructor([param('ns3::Channel const &', 'arg0')])
cls.add_constructor([])
cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True)
cls.add_method('GetId', 'uint3... |
class MLP(nn.Module):
def __init__(self, input_dim=2048, embed_dim=768):
super().__init__()
self.proj = nn.Linear(input_dim, embed_dim)
def forward(self, x):
x = x.flatten(2).transpose(1, 2)
x = self.proj(x)
return x |
def build_treebank(trees, transition_scheme=TransitionScheme.TOP_DOWN_UNARY, reverse=False):
if reverse:
return [build_sequence(tree.reverse(), transition_scheme) for tree in trees]
else:
return [build_sequence(tree, transition_scheme) for tree in trees] |
def transform_tree(tree, fn, iterable_type=tuple):
if is_iterable(tree):
if isinstance(tree, dict):
res = tree.__new__(type(tree))
res.__init__(((k, transform_tree(child, fn)) for (k, child) in iteritems(tree)))
return res
elif isinstance(tree, tuple):
... |
def test_mirror():
STATE_LEN = 1000
FIDELITY = 0.98
LS_FREQ = .0
MEAN = 0.1
tl = Timeline()
ls = LightSource('ls', tl, frequency=LS_FREQ, mean_photon_num=MEAN)
sender = EmittingNode('sender', tl, ls)
receiver = Receiver('receiver', tl)
mr = Mirror('mr', tl, fidelity=FIDELITY, destina... |
class ToggleObjectAction(BaseAction):
valid_actions = {'ToggleObjectOn', 'ToggleObjectOff'}
def get_reward(self, state, prev_state, expert_plan, goal_idx):
if (state.metadata['lastAction'] not in self.valid_actions):
(reward, done) = (self.rewards['invalid_action'], False)
return... |
def main(_):
vocab = Vocabulary.from_file(os.path.join(FLAGS.datadir, '1b_word_vocab.txt'))
dataset = Dataset(vocab, os.path.join(FLAGS.datadir, 'training-monolingual.tokenized.shuffled/*'))
single_gpu_graph = tf.Graph()
with single_gpu_graph.as_default():
with tf.variable_scope('model'):
... |
class Conv_Block(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, num_conv_layers=3, dilation_rate=2):
super(Conv_Block, self).__init__()
self.num_conv_layers = num_conv_layers
self.input_dim = in_channels
self.output_dim = out_channels
ops = []
... |
def compute_bench(samples_range, features_range):
it = 0
results = dict()
lars = np.empty((len(features_range), len(samples_range)))
lars_gram = lars.copy()
omp = lars.copy()
omp_gram = lars.copy()
max_it = (len(samples_range) * len(features_range))
for (i_s, n_samples) in enumerate(samp... |
def get_gradnorm(optimizer, group=0):
norms = [torch.norm(p.grad).item() for p in optimizer.param_groups[group]['params']]
gradnorm = (np.mean(norms) if norms else 0)
return gradnorm |
_properties
class Stream(Data):
offset = ListProperty(element_type=symbolic.pystr_to_symbolic)
buffer_size = SymbolicProperty(desc='Size of internal buffer.', default=0)
def __init__(self, dtype, buffer_size, shape=None, transient=False, storage=dtypes.StorageType.Default, location=None, offset=None, lifeti... |
def create_mention_span_representations(mentions, model, device, topic_docs, is_event, requires_grad):
for mention in mentions:
mention.span_rep = get_mention_span_rep(mention, device, model, topic_docs, is_event, requires_grad) |
def conv(in_planes, out_planes, dilation=1, kernel_size=3, stride=1):
return nn.Sequential(nn.Conv2d(in_planes, out_planes, dilation=dilation, kernel_size=kernel_size, stride=stride, padding=(((kernel_size - 1) + ((kernel_size - 1) * (dilation - 1))) // 2)), nn.GroupNorm(1, out_planes), nn.ReLU(inplace=True)) |
def _dump_protobuf(args, proto, prefix, depth):
if args.dump_verbose:
if (0 <= depth <= len(prefix)):
print('{} ...'.format(':'.join(prefix)))
return
for (desc, field) in proto.ListFields():
if isinstance(field, (int, float, complex, str)):
print('... |
class EarlyStopping():
def __init__(self, patience=7, verbose=False, delta=0):
self.patience = patience
self.verbose = verbose
self.counter = 0
self.best_score = None
self.early_stop = False
self.val_loss_min = np.Inf
self.delta = delta
def __call__(self, ... |
def add_value_info_as_variable(network, info):
if (not info.type.HasField('tensor_type')):
raise ValueError("Only TensorProto is allowed as ValueInfoProto's type for info.name (Got {})".format(info.name, info.type))
t = info.type.tensor_type
v = network.variable.add()
v.name = info.name
shap... |
def test_simple():
a = ak.from_numpy(np.array([[1, 2], [3, 4], [5, 6]]), regulararray=True)
b = ak.from_numpy(np.array([[7, 8], [9, 10]]), regulararray=True)
c = a.layout._mergemany([b.layout])
assert isinstance(c, ak.contents.RegularArray)
assert (c.size == 2)
assert (ak.operations.to_list(c) =... |
def main(config):
cudnn.benchmark = True
if config.train:
make_folder(config.model_save_path, config.version)
make_folder(config.sample_path, config.version)
make_folder(config.log_path, config.version)
data_loader = Data_Loader(config.img_path, config.label_path, config.imsize, ... |
def read_init():
with open(os.path.join(PATH_TO_TRANSFORMERS, '__init__.py'), 'r', encoding='utf-8', newline='\n') as f:
lines = f.readlines()
line_index = 0
while (not lines[line_index].startswith('if TYPE_CHECKING')):
line_index += 1
backend_specific_objects = {}
while (line_index ... |
def get_grouped_params(model, args, no_decay=['bias', 'LayerNorm.weight']):
(params_with_wd, params_without_wd) = ([], [])
for (n, p) in model.named_parameters():
if any(((nd in n) for nd in no_decay)):
params_without_wd.append(p)
else:
params_with_wd.append(p)
return... |
class RootMeanSquaredError(NumpyArrayMetric):
def __init__(self, metric: str='RMSE'):
super().__init__(metric)
def calculate(self):
return np.sqrt(np.mean(np.square((self.reference - self.prediction)))) |
def argmax_output_model(input_shape):
inputs = layers.Input(shape=input_shape)
x = layers.Conv2D(3, 3)(inputs)
x = layers.BatchNormalization()(x)
x = layers.Conv2D(3, 3)(x)
x = layers.ReLU()(x)
outputs = tf.argmax(x, axis=(- 1))
model = keras.Model(inputs=inputs, outputs=outputs)
return ... |
def main():
args = parse_args()
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(message)s')
args.out_dir.mkdir(exist_ok=True, parents=True)
(args.out_dir / 'train').mkdir(exist_ok=True)
(args.out_dir / 'test').mkdir(exist_ok=True)
data = utils.load_csv_text(args.in_filename,... |
class GPT2TokenizerFast(PreTrainedTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ['input_ids', 'attention_mask']
slow_tokenizer_class = GPT2Tokenizer
... |
def _get_approximate_success(prev_rgb, frame, action):
wheres = np.where((prev_rgb != frame))
wheres_ar = np.zeros(prev_rgb.shape)
wheres_ar[wheres] = 1
wheres_ar = np.sum(wheres_ar, axis=2).astype(bool)
connected_regions = skimage.morphology.label(wheres_ar, connectivity=2)
unique_labels = [i f... |
def simple_multi_input_reduce_tests(rank, world_size):
return [(c10d.ReduceOp.SUM, [torch.tensor([((2 * rank) + 0.0)]), torch.tensor([((2 * rank) + 1.0)])], torch.tensor([float((world_size * ((2 * world_size) - 1)))])), (c10d.ReduceOp.PRODUCT, [torch.tensor([((2 * rank) + 1.0)]), torch.tensor([((2 * rank) + 2.0)])]... |
.parametrize('lil_container', LIL_CONTAINERS)
def test_sample_weights(lil_container):
X_sp = lil_container(X)
clf = svm.SVC()
clf.fit(X_sp, Y)
assert_array_equal(clf.predict([X[2]]), [1.0])
sample_weight = (([0.1] * 3) + ([10] * 3))
clf.fit(X_sp, Y, sample_weight=sample_weight)
assert_array_... |
def all_gather_list(data, max_size=4096):
world_size = hvd.size()
if ((not hasattr(all_gather_list, '_in_buffer')) or (max_size != all_gather_list._in_buffer.size())):
all_gather_list._in_buffer = torch.cuda.ByteTensor(max_size)
in_buffer = all_gather_list._in_buffer
enc = pickle.dumps(data)
... |
def sgd(opfunc, x, config, state=None):
state = (state if (state is not None) else config)
lr = config.get('learningRate', 0.001)
lrd = config.get('learningRateDecay', 0)
wd = config.get('weightDecay', 0)
mom = config.get('momentum', 0)
damp = config.get('dampening', mom)
nesterov = config.g... |
_model
def caformer_s18_in21ft1k(pretrained=False, **kwargs):
model = MetaFormer(depths=[3, 3, 9, 3], dims=[64, 128, 320, 512], token_mixers=[SepConv, SepConv, Attention, Attention], head_fn=MlpHead, **kwargs)
model.default_cfg = default_cfgs['caformer_s18_in21ft1k']
if pretrained:
state_dict = torc... |
def gen_normals_kernel_indexed(vertices: template(), indices: template(), normals: template(), weights: template()):
num_triangles = (indices.shape[0] // 3)
num_vertices = vertices.shape[0]
for i in range(num_vertices):
normals[i] = Vector([0.0, 0.0, 0.0])
weights[i] = 0.0
for i in range... |
def MODEL(model_name, scope, weight_decay, image, label, is_training, Distillation):
network_fn = nets_factory.get_network_fn(model_name, weight_decay=weight_decay)
end_points = network_fn(image, label, scope, is_training=is_training, Distill=Distillation)
loss = tf.losses.softmax_cross_entropy(label, end_p... |
def register_pascal_voc(name, dirname, split, year, class_names=CLASS_NAMES):
DatasetCatalog.register(name, (lambda : load_voc_instances(dirname, split, class_names)))
MetadataCatalog.get(name).set(thing_classes=list(class_names), dirname=dirname, year=year, split=split) |
_cache(maxsize=1024)
def unit_nhops_to_proc_region(layer, batch_size, region, part, filter_nodes, ifmap_layout, ofmap_layout, options):
fil_dict = {}
ofm_dict = {}
ifm_dict = {}
for pidx in part.gen_pidx():
coord = part.coordinate(region, pidx)
(filrng, ifrng, ofrng) = proc_data_range(la... |
.corpus
def test_snips():
config = dotenv_values()
dataset_root = config['SNIPS']
dataset = SNIPS(dataset_root, ['Ivy', 'Joanna', 'Joey', 'Justin', 'Kendra', 'Kimberly', 'Matthew', 'Salli'], ['Aditi', 'Amy', 'Geraint', 'Nicole'], ['Brian', 'Emma', 'Raveena', 'Russell'])
(train_data, valid_data, test_dat... |
class PlayerState(object):
def __init__(self, position, orientation, held_object=None):
self.position = tuple(position)
self.orientation = tuple(orientation)
self.held_object = held_object
assert (self.orientation in Direction.ALL_DIRECTIONS)
if (self.held_object is not None)... |
def make_learner_xml(path, filename='korean_learner_corpus_error_sentences.xml'):
all = []
for filename in os.listdir(path):
all.extend(parse_xml(((path + '/') + filename)))
root_node = xmlparser.Element('root')
[root_node.append(e) for e in all]
xmlparser.ElementTree(root_node).write(filena... |
def test_Absorptive_expire():
tl = Timeline()
mem = AbsorptiveMemory('mem', tl, .0, 1, perfect_efficiency, 100, 500)
parent = DumbParent(mem)
process = Process(mem, 'expire', [])
event = Event(.0, process)
tl.schedule(event)
mem.expiration_event = event
mem._schedule_expiration()
cou... |
class TableauTuples_all(TableauTuples):
def __init__(self):
super().__init__(category=Sets())
self._level = None
self._size = None
def _repr_(self):
return 'Tableau tuples'
def an_element(self):
return self.element_class(self, [[[1]], [[2]], [[3]], [[4]], [[5]], [[6]]... |
def one_hot(x: torch.Tensor, v_bins: torch.Tensor) -> torch.Tensor:
reshaped_bins = v_bins.view((((1,) * len(x.shape)) + (len(v_bins),)))
diffs = (x[(..., None)] - reshaped_bins)
am = torch.argmin(torch.abs(diffs), dim=(- 1))
return nn.functional.one_hot(am, num_classes=len(v_bins)).float() |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [313])
.parametrize('x_shape, q_shape', [((4, 8, 16, 16), (1, 1, 1, 1)), ((4, 8, 16, 16), (1, 8, 1, 1)), ((16, 8, 3, 3), (16, 1, 1, 1))])
.parametrize('decay', [0.999, 0.9])
.parametrize('x_min_max', [True, False])
.parametrize('ema', [True, False])
.parametrize... |
class LoraHandler(object):
def __init__(self, version: LORA_VERSIONS=LoraVersions.cloneofsimo, use_unet_lora: bool=False, use_text_lora: bool=False, save_for_webui: bool=False, only_for_webui: bool=False, lora_bias: str='none', unet_replace_modules: list=None, text_encoder_replace_modules: list=None):
self.... |
class Adapter(ABC):
def __init__(self, adapter_spec: AdapterSpec, tokenizer_service: TokenizerService):
self.adapter_spec: AdapterSpec = adapter_spec
self.window_service: WindowService = WindowServiceFactory.get_window_service(adapter_spec.model_deployment, tokenizer_service)
def adapt(self, ins... |
.expansion
class ExpandStencilIntelFPGA(dace.library.ExpandTransformation):
environments = []
def expansion(node, parent_state, parent_sdfg):
sdfg = dace.SDFG((node.label + '_outer'))
state = sdfg.add_state((node.label + '_outer'))
(inputs, outputs, shape, field_to_data, field_to_desc, f... |
def _wsgi_test(case: Case, checks: Iterable[CheckFunction], targets: Iterable[Target], result: TestResult, headers: dict[(str, Any)], store_interactions: bool, feedback: Feedback, max_response_time: (int | None)) -> WSGIResponse:
with catching_logs(LogCaptureHandler(), level=logging.DEBUG) as recorded:
star... |
class _MemoryEfficientFP16OptimizerMixin(object):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._multiply_factor = 1.0
def has_flat_params(self):
return False
def state_dict(self):
state_dict = self.wrapped_optimizer.state_dict()
if (self... |
def gaussian_measure_2d_full(mean, cov, f):
if (not is_pos_def(cov)):
logger.warn(f'cov={cov} not positive definite')
L = cholesky(cov)
def integrand(x2, x1):
(y1, y2) = ((L [x1, x2]) + mean)
return ((norm_pdf(x1) * norm_pdf(x2)) * f(y1, y2))
integral = dblquad(integrand, (- 10)... |
('/get_gas_limits/<lastN>', methods=('GET',))
def get_gas_limits(lastN):
web3 = connect_to_geth(app.web3_url, app.consensus)
latest = web3.eth.getBlock('latest').number
start = ((latest - int(lastN)) + 1)
if (start <= 0):
start = 1
gas_limits = {}
for bk in range(start, (latest + 1)):
... |
_pooler('average_concat_last_k')
class AverageConcatLastN(nn.Module):
def __init__(self, k=4, tol=1e-06):
super().__init__()
self.num_layers = k
self.tol = tol
def forward(self, encoded_layers: List[torch.Tensor], pad_mask: torch.Tensor):
assert (self.num_layers <= len(encoded_la... |
class Spinner(Infinite):
phases = ('-', '\\', '|', '/')
hide_cursor = True
def update(self):
i = (self.index % len(self.phases))
self.write(self.phases[i]) |
class RobertaPreLayerNormForMaskedLM(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class RandomCycler():
def __init__(self, source):
if (len(source) == 0):
raise Exception("Can't create RandomCycler from an empty collection")
self.all_items = list(source)
self.next_items = []
def sample(self, count: int):
shuffle = (lambda l: random.sample(l, len(l)... |
class HashError(InstallationError):
req = None
head = ''
order = None
def body(self):
return ' {}'.format(self._requirement_name())
def __str__(self):
return '{}\n{}'.format(self.head, self.body())
def _requirement_name(self):
return (str(self.req) if self.req else 'un... |
()
('--seed', default=1)
('--max_path_length', default=150)
('--meta_batch_size', default=10)
('--n_epochs', default=10)
('--episode_per_task', default=10)
_experiment
def rl2_ppo_metaworld_ml10(ctxt, seed, max_path_length, meta_batch_size, n_epochs, episode_per_task):
set_seed(seed)
with LocalTFRunner(snapshot... |
def _seg_68():
return [(120700, 'M', u''), (120701, 'M', u''), (120702, 'M', u''), (120703, 'M', u''), (120704, 'M', u''), (120705, 'M', u''), (120707, 'M', u''), (120708, 'M', u''), (120709, 'M', u''), (120710, 'M', u''), (120711, 'M', u''), (120712, 'M', u''), (120713, 'M', u''), (120714, 'M', u''), (120715, 'M',... |
class WhisperModel(nn.Module):
def __init__(self, model_type='small.en', n_class=14):
super().__init__()
self.encoder = whisper.load_model(model_type).encoder
for param in self.encoder.parameters():
param.requires_grad = True
feature_dim = 768
self.intent_classifi... |
def get_combinations(list1, list2):
return [list(zip(each_permutation, list2)) for each_permutation in itertools.permutations(list1, len(list2))] |
def open_all_layers(model):
model.train()
for p in model.parameters():
p.requires_grad = True |
def nested_map_for_loop_2(B: dace.int64[(10, 10)]):
A = np.ndarray([10, 10], dtype=np.int64)
for i in dace.map[0:10]:
for j in range(10):
A[(i, j)] = (((2 * B[(i, j)]) + (i * 10)) + j)
return A |
def mean_IoU(overall_h):
iu = (np.diag(overall_h) / ((overall_h.sum(1) + overall_h.sum(0)) - np.diag(overall_h)))
return (iu, np.nanmean(iu)) |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [313])
.parametrize('val', [0.5, 1, 2])
def test_mul_scalar_forward_backward(seed, val, ctx, func_name):
from nbla_test_utils import function_tester
rng = np.random.RandomState(seed)
inputs = [(rng.randn(2, 3, 4).astype(np.float32) * 2)]
function... |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [313])
def test_tan_double_backward(seed, ctx, func_name):
from nbla_test_utils import cap_ignore_region, backward_function_tester
rng = np.random.RandomState(seed)
inputs = [(np.clip(rng.randn(2, 3, 4).astype(np.float32), ((- np.pi) / 2), (np.pi / 2... |
def find_files(top_directory, exclude=[], include_top_directory_in_name=True):
import os
import re
paths_and_names = []
exclude = [re.compile(exclusion) for exclusion in exclude]
top_directory = os.path.abspath(os.path.expanduser(top_directory))
parent_directory = os.path.dirname(top_directory)
... |
def main(_):
if (not os.path.exists(args.checkpoint_dir)):
os.makedirs(args.checkpoint_dir)
if (not os.path.exists(args.sample_dir)):
os.makedirs(args.sample_dir)
if (not os.path.exists(args.test_dir)):
os.makedirs(args.test_dir)
tfconfig = tf.ConfigProto(allow_soft_placement=Tru... |
def seqtemplate1(seq_label):
question = 'Is this sentence Causal or Non-causal?'
answers = {'text': [('Causal' if (int(seq_label) == 1) else 'Non-causal')]}
return (question, answers) |
def cross_entropy(output, target):
return F.binary_cross_entropy_with_logits(input=output, target=target.float()) |
class IStat():
def __init__(self, value: float=None, n: int=0):
if (n > 0):
assert (value is not None)
self.value = value
self.n = n
def n(self):
return self._n
def n(self, n: int):
assert (n >= 0)
self._n = n
def value(self):
return se... |
class VessNN(nn.Module):
def __init__(self):
super(VessNN, self).__init__()
self.conv1 = nn.Sequential(nn.Conv3d(1, 24, (2, 3, 3)), nn.ReLU(), nn.Conv3d(24, 24, (2, 3, 3)), nn.ReLU(), nn.Conv3d(24, 24, (2, 3, 3)), nn.Tanh(), nn.MaxPool3d((1, 2, 2), stride=(1, 1, 1)))
self.conv2 = nn.Sequenti... |
_seed
.parametrize('num_steps, acquisition_rule', [pytest.param(5, EfficientGlobalOptimization(), id='EfficientGlobalOptimization'), pytest.param(10, DiscreteThompsonSampling(1000, 1), id='DiscreteThompsonSampling'), pytest.param(5, DiscreteThompsonSampling(1000, 1, thompson_sampler=ThompsonSamplerFromTrajectory()), id... |
class config_fc(Command):
description = 'specify Fortran 77/Fortran 90 compiler information'
user_options = [('fcompiler=', None, 'specify Fortran compiler type'), ('f77exec=', None, 'specify F77 compiler command'), ('f90exec=', None, 'specify F90 compiler command'), ('f77flags=', None, 'specify F77 compiler fl... |
def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &'... |
def nnb_template(args, ifiles, output):
nnp = _import_file(args, ifiles)
if (nnp is not None):
return _generate_nnb_template(args, nnp, output)
else:
print('Import from [{}] failed.'.format(ifiles))
return False |
class BadArgumentUsage(UsageError):
def __init__(self, message, ctx=None):
UsageError.__init__(self, message, ctx) |
class CoNLLDataset(object):
def __init__(self, filename, processing_word=None, processing_tag=None, max_iter=None):
self.filename = filename
self.processing_word = processing_word
self.processing_tag = processing_tag
self.max_iter = max_iter
self.length = None
def __iter_... |
.box(NumpyType)
def NumpyType_box(typ, val, c):
Numpy_obj = c.pyapi.unserialize(c.pyapi.serialize_object(Numpy))
from_buffer_obj = c.pyapi.object_getattr_string(Numpy_obj, '_from_buffer')
builder = numba.core.cgutils.create_struct_proxy(typ)(c.context, c.builder, value=val)
data_obj = c.pyapi.from_nativ... |
def df_to_time_series(df: pd.DataFrame, time_col: str=None, timestamp_unit='s', data_cols: Union[(str, List[str])]=None) -> TimeSeries:
if (not isinstance(df.index, pd.DatetimeIndex)):
if (time_col is None):
time_col = df.columns[0]
elif (time_col not in df.columns):
raise Ke... |
class VAE(nn.Module):
def __init__(self, in_dim, hidden_dim, latent_dim, conditional=False, condition_dim=None):
super().__init__()
self.latent_dim = latent_dim
self.conditional = conditional
if (self.conditional and (condition_dim is not None)):
input_dim = (in_dim + con... |
def _predict(x: Text):
x = x.split(sep='[SEP]')
inputs = [{'context': y[0], 'question': y[1]} for y in x]
outputs = model(inputs)
if isinstance(outputs, dict):
outputs = [outputs]
return [output['answer'] for output in outputs] |
def _open_file_context(file_like, appendmat, mode='rb'):
(f, opened) = _open_file(file_like, appendmat, mode)
try:
(yield f)
finally:
if opened:
f.close() |
_start_docstrings('T5 Model with a `language modeling` head on top. ', T5_START_DOCSTRING)
class T5ForConditionalGeneration(T5PreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.model_dim = config.d_model
self.shared = nn.Embedding(config.vocab_size, config.d_model)
... |
def _validate_index(episode: EpisodeBase, index: int) -> None:
assert (index < episode.transition_count) |
class RnnEncoder(torch.nn.Module):
def __init__(self, hidden_size, in_channel, encoding_size, cell_type='GRU', num_layers=1, device='cpu', dropout=0, bidirectional=True):
super(RnnEncoder, self).__init__()
self.hidden_size = hidden_size
self.in_channel = in_channel
self.num_layers = ... |
def masked_hit_miss_counts(pred, gt, mask, thresholds):
from nowcasting.hko_evaluation import rainfall_to_pixel
thresholds = [rainfall_to_pixel(threshold) for threshold in thresholds]
hits = []
misses = []
false_alarms = []
correct_negatives = []
for threshold in thresholds:
pred_rai... |
def persist(key: str) -> str:
if (_PERSIST_STATE_KEY not in st.session_state):
st.session_state[_PERSIST_STATE_KEY] = set()
st.session_state[_PERSIST_STATE_KEY].add(key)
return key |
def has_valid_annotation(anno, ann_types, filter_crowd=True):
if (len(anno) == 0):
return False
if filter_crowd:
if ('iscrowd' in anno[0]):
anno = [obj for obj in anno if (obj['iscrowd'] == 0)]
if (len(anno) == 0):
return False
if _has_only_empty_bbox(anno):
r... |
def register_Ns3CallbackImplBase_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True)
cls.add_method('IsEqual', 'bool', [param('ns3::Pt... |
_function_dispatch(_strip_dispatcher)
def rstrip(a, chars=None):
a_arr = numpy.asarray(a)
return _vec_string(a_arr, a_arr.dtype, 'rstrip', (chars,)) |
_params({'labels_true': ['array-like'], 'labels_pred': ['array-like'], 'average_method': [StrOptions({'arithmetic', 'max', 'min', 'geometric'})]}, prefer_skip_nested_validation=True)
def normalized_mutual_info_score(labels_true, labels_pred, *, average_method='arithmetic'):
(labels_true, labels_pred) = check_cluste... |
def get_predicted_probabilities(p1, p2, p3, p4):
prob_all_4 = (((p1 * p2) * p3) * p4)
prob_exactly_3 = (((((((1 - p1) * p2) * p3) * p4) + (((p1 * (1 - p2)) * p3) * p4)) + (((p1 * p2) * (1 - p3)) * p4)) + (((p1 * p2) * p3) * (1 - p4)))
list_of_probs = [p1, p2, p3, p4]
prob_exactly_2 = 0
for i in rang... |
class ResnetUtilsTest(tf.test.TestCase):
def testSubsampleThreeByThree(self):
x = tf.reshape(tf.to_float(tf.range(9)), [1, 3, 3, 1])
x = resnet_utils.subsample(x, 2)
expected = tf.reshape(tf.constant([0, 2, 6, 8]), [1, 2, 2, 1])
with self.test_session():
self.assertAllClo... |
def run_hp_search_ray(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
import ray
def _objective(trial, local_trainer, checkpoint_dir=None):
checkpoint = None
if checkpoint_dir:
for subdir in os.listdir(checkpoint_dir):
if subdir.startswith(PREFIX_CHECKPO... |
def arg_parse():
parser = argparse.ArgumentParser(description='GcnInformax Arguments.')
parser.add_argument('--target', dest='target', type=int, default=0, help='')
parser.add_argument('--train-num', dest='train_num', type=int, default=5000)
parser.add_argument('--use-unsup-loss', dest='use_unsup_loss',... |
def iter21(num):
for idiag in range(num):
(irs, ics) = nm.diag_indices((num - idiag))
for ii in range(irs.shape[0]):
(yield ((irs[ii] + idiag), ics[ii])) |
class RouterGAP(nn.Module):
def __init__(self, input_nc, input_width, input_height, ngf=5, kernel_size=7, soft_decision=True, stochastic=False, **kwargs):
super(RouterGAP, self).__init__()
self.ngf = ngf
self.soft_decision = soft_decision
self.stochastic = stochastic
if (max(... |
def _linear_transform(attributions, clip_above_percentile=99.9, clip_below_percentile=70.0, low=0.2):
if ((clip_above_percentile < 0) or (clip_above_percentile > 100)):
raise ValueError('clip_above_percentile must be in [0, 100]')
if ((clip_below_percentile < 0) or (clip_below_percentile > 100)):
... |
def collect_results_cpu(result_part, size, tmpdir=None):
(rank, world_size) = get_dist_info()
if (tmpdir is None):
MAX_LEN = 512
dir_tensor = torch.full((MAX_LEN,), 32, dtype=torch.uint8, device='cuda')
if (rank == 0):
mmcv.mkdir_or_exist('.dist_test')
tmpdir = te... |
def main(argv):
ns = rospy.get_namespace()
ns = ns[0:(- 1)]
csvfile = argv[0]
dbcfile = argv[1]
node = lead_drive(ns, csvfile, dbcfile)
while (not rospy.is_shutdown()):
node.publish()
if (node.next_time == (- 1)):
break
deltaT = (node.next_time - node.current_... |
def convert_onnx_proto(attribute):
from daceml.onnx.schema import ONNXAttributeType, _KNOWN_ONNX_PROTOS, ONNXParameterType
if (type(attribute) in _KNOWN_ONNX_PROTOS):
return _KNOWN_ONNX_PROTOS[type(attribute)].from_onnx_proto(attribute)
if isinstance(attribute, (int, str, bool, float)):
retu... |
_module('numpy')
def info(object=None, maxwidth=76, output=sys.stdout, toplevel='numpy'):
global _namedict, _dictlist
import pydoc
import inspect
if (hasattr(object, '_ppimport_importer') or hasattr(object, '_ppimport_module')):
object = object._ppimport_module
elif hasattr(object, '_ppimpor... |
def link_classification(output_dim: int=1, output_act: AnyStr='sigmoid', edge_embedding_method: AnyStr='ip'):
edge_function = link_inference(output_dim=output_dim, output_act=output_act, edge_embedding_method=edge_embedding_method, name='link_classification')
return edge_function |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.