code stringlengths 101 5.91M |
|---|
class Conv1_1_Branch(nn.Module):
def __init__(self, in_ch, block_ch):
super(Conv1_1_Branch, self).__init__()
self.conv1_1 = nn.Sequential(nn.Conv1d(in_channels=in_ch, out_channels=block_ch, kernel_size=1, stride=1, padding=0, bias=False), nn.BatchNorm1d(block_ch, affine=False, track_running_stats=Tr... |
_REGISTRY.register()
class DescribableTextures(DatasetBase):
dataset_dir = 'dtd'
def __init__(self, cfg):
root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT))
self.dataset_dir = os.path.join(root, self.dataset_dir)
self.image_dir = os.path.join(self.dataset_dir, 'images')
... |
def safe_log(a: Tensor, *, eps: Optional[float]=None) -> Tensor:
if (eps is None):
eps = {'float16': 6e-08, 'bfloat16': 9.1835e-41, 'float32': 1.4013e-45, 'float64': 5e-324}[a.dtype]
return a._raw_backend.safe_log(a, eps=eps) |
class Binarizer():
def binarize(filename, dict, consumer, tokenize=tokenize_line, append_eos=True, reverse_order=False, offset=0, end=(- 1)):
(nseq, ntok) = (0, 0)
replaced = Counter()
def replaced_consumer(word, idx):
if ((idx == dict.unk_index) and (word != dict.unk_word)):
... |
def parse_args():
parser = argparse.ArgumentParser('Generating annotations for spatial 3D reference (Sr3D).')
parser.add_argument('-preprocessed_scannet_file', type=str, help='.pkl (output) of prepare_scannet_data.py', required=True)
parser.add_argument('-valid_targets_file', type=str, help='.txt file descr... |
class DonutSwinModelTester():
def __init__(self, parent, batch_size=13, image_size=32, patch_size=2, num_channels=3, embed_dim=16, depths=[1, 2, 1], num_heads=[2, 2, 4], window_size=2, mlp_ratio=2.0, qkv_bias=True, hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, drop_path_rate=0.1, hidden_act='gelu', use... |
def parse_args():
import argparse
parser = argparse.ArgumentParser('Script for subsampling particles from a coordinates table')
parser.add_argument('file', help='path to particle coordinates file')
parser.add_argument('-n', '--number', type=int, help='number of particles to sample')
parser.add_argum... |
def compute_all_speedups(seq_gpipe_dict, seq_gpipe_times, seq_stale_dict, seq_stale_times, virtual_gpipe_dict, virtual_stale_dict, virtual_times_gpipe, virtual_times_stale, skip_gpipe_seq=False):
if (not skip_gpipe_seq):
time_to_best_result(seq_gpipe_dict, virtual_stale_dict, seq_gpipe_times, virtual_times_... |
class Annotator(Callback):
def __init__(self, cfg):
self.envs = None
self.cfg = cfg
self.device = None
self.lang_folder = cfg.lang_folder
self.tasks = hydra.utils.instantiate(cfg.callbacks.rollout.tasks)
self.demo_task_counter_train = Counter()
self.demo_task_... |
_on_pypy
def test_inherited_protocol():
matrix = m.SquareMatrix(5)
assert (memoryview(matrix).shape == (5, 5))
assert (np.asarray(matrix).shape == (5, 5)) |
def get_module(module):
backbones = inspect.getmembers(Modules)
_cls = [_c for (name, _c) in backbones if (name == module)]
return _cls[0] |
class no_grad(object):
def __init__(self):
self.prev = torch.is_grad_enabled()
def __enter__(self):
torch._C.set_grad_enabled(False)
def __exit__(self, *args):
torch.set_grad_enabled(self.prev)
return False
def __call__(self, func):
(func)
def decorate_no_... |
def no_default_args_signature(type_system):
return InferredSignature(signature=inspect.Signature(parameters=[inspect.Parameter(name='a', kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=float), inspect.Parameter(name='b', kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=float), inspect.Parameter(nam... |
def get_args():
import argparse
parser = argparse.ArgumentParser(description='For EAD2019 challenge: semantic segmentation', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--generalizationMetric_seg_1', type=str, default='../Result_test/metrics_det_EAD2020.json', help='json fil... |
def _convert_python_version(value):
if (not value):
return (None, None)
parts = value.split('.')
if (len(parts) > 3):
return ((), 'at most three version parts are allowed')
if (len(parts) == 1):
value = parts[0]
if (len(value) > 1):
parts = [value[0], value[1:... |
class GluePartitioner(PartitioningTask):
def __init__(self, args) -> None:
super().__init__(args)
self.tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, do_lower_case=args.do_lower_case, cache_dir=(args.cache_dir if args.cache_dir else None))
def batch_dim(self) -> int:
... |
def save_wiki_pickle(wiki_map, pathp='./'):
if path.exists((pathp + 'wiki_map.pickle')):
old_wiki_map = get_wiki_pickle()
for (k, v) in old_wiki_map.items():
if (k not in wiki_map):
wiki_map[k] = v
with open((pathp + 'wiki_map.pickle'), 'wb') as handle:
pickle... |
def _load_vocabulary(filename):
tf.logging.info('Reading vocabulary from %s', filename)
vocab = collections.OrderedDict()
with tf.gfile.GFile(filename, mode='r') as f:
for (i, line) in enumerate(f):
word = line.decode('utf-8').strip()
assert (word not in vocab), ('Attempting ... |
class BaseMetric(ABC):
def __init__(self):
self.score = None
def update(self, y_true, y_pred):
pass
def get(self):
return self.score |
class AwaitIterNextExprNode(AwaitExprNode):
def _generate_break(self, code):
code.globalstate.use_utility_code(UtilityCode.load_cached('StopAsyncIteration', 'Coroutine.c'))
code.putln('PyObject* exc_type = __Pyx_PyErr_Occurred();')
code.putln('if (unlikely(exc_type && (exc_type == __Pyx_PyEx... |
def fig_posterior(task_name: str, num_observation: int=1, num_samples: int=1000, prior: bool=False, reference: bool=True, true_parameter: bool=False, samples_path: Optional[str]=None, samples_tensor: Optional[torch.Tensor]=None, samples_name: Optional[str]=None, samples_color: Optional[str]=None, title: Optional[str]=N... |
class Resnet101Triplet(nn.Module):
def __init__(self, embedding_dimension=512, pretrained=False):
super(Resnet101Triplet, self).__init__()
self.model = resnet101(pretrained=pretrained)
input_features_fc_layer = self.model.fc.in_features
self.model.fc = nn.Linear(input_features_fc_lay... |
.script
def inv_apply_mean_var(x, mean, var, eps):
stdev = torch.sqrt(torch.max(var, eps))
return torch.addcmul(mean.to(x.dtype), stdev.to(x.dtype), x, value=1.0) |
def fill_standard_subplot(axis, x_vals_unsorted, y_vals_unsorted, label, available_items_scaling, max_depth):
sorted_pairs = sorted(zip(x_vals_unsorted, y_vals_unsorted), key=(lambda x: x[0]))
if (len(sorted_pairs) > 0):
(x_vals, y_vals) = map(list, zip(*sorted_pairs))
else:
x_vals = x_vals_... |
def _to_array_with_correct_type(obj: Any) -> np.ndarray:
if (isinstance(obj, np.ndarray) and issubclass(obj.dtype.type, (np.bool_, np.number))):
return obj
obj_array = np.asanyarray(obj)
if (not issubclass(obj_array.dtype.type, (np.bool_, np.number))):
obj_array = obj_array.astype(object)
... |
def get_top_n(root: Path, n_speakers: int=10, min_n_tokens: int=5) -> pd.DataFrame:
df = load_df_from_tsv((root / 'validated.tsv'))
df['n_tokens'] = [len(s.split()) for s in df['sentence']]
df = df[(df['n_tokens'] >= min_n_tokens)]
df['n_frames'] = [torchaudio.info(((root / 'clips') / p).as_posix()).num... |
.skipif((sys.version_info[0] < 3), reason='NumPy exposes slightly different functions on Python 2')
def test_numpy_namespace():
undocumented = {'Tester': 'numpy.testing._private.nosetester.NoseTester', '_add_newdoc_ufunc': 'numpy.core._multiarray_umath._add_newdoc_ufunc', 'add_docstring': 'numpy.core._multiarray_um... |
def run_program(sdfg):
in0 = np.zeros((16,), np.float32)
in1 = np.ones((16,), np.float32)
in2 = np.ones((16,), np.float32)
out0 = np.empty((16,), np.float32)
out1 = np.empty((16,), np.float32)
sdfg(in0=in0, in1=in1, in2=in2, out0=out0, out1=out1)
assert np.allclose(out0, (2 * ((in0 + 1) + (i... |
class ConfigError(InputError):
def __init__(self, message='The config file contains an error.'):
super().__init__(f'CONFIG ERROR: {message}') |
class Head(nn.Module):
num_features: int
num_classes: int = 1000
global_pool: str = 'avg'
drop_rate: float = 0.0
dtype: Dtype = jnp.float32
conv_layer: ModuleDef = conv2d
norm_layer: ModuleDef = batchnorm2d
linear_layer: ModuleDef = linear
act_fn: Callable = nn.relu
def __call__(... |
def register_Ns3Packet_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_constructor([])
cls.add_constructor([param('ns3::Packet const &', 'o')])
cls.add_constructor([param('uint32_t', 'size')])
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), par... |
class SentenceTransformersVectorizer(BaseSentenceVectorizer):
def __init__(self, model_name_or_path: str='all-MiniLM-L6-v2', vectorize_bs: int=256, max_gpu_devices: int=1, normalize_embeddings: bool=False):
try:
from sentence_transformers import SentenceTransformer
except ImportError as ... |
def randomGaussian(image, mean=0.1, sigma=0.35):
def gaussianNoisy(im, mean=mean, sigma=sigma):
for _i in range(len(im)):
im[_i] += random.gauss(mean, sigma)
return im
img = np.asarray(image)
(width, height) = img.shape
img = gaussianNoisy(img[:].flatten(), mean, sigma)
i... |
class JumanppTokenizer():
def __init__(self, do_lower_case=False, never_split=None, normalize_text=True, trim_whitespace=False):
self.do_lower_case = do_lower_case
self.never_split = (never_split if (never_split is not None) else [])
self.normalize_text = normalize_text
self.trim_whi... |
_dispatch
def fft2(x, s=None, axes=((- 2), (- 1)), norm=None, overwrite_x=False, workers=None, *, plan=None):
return (Dispatchable(x, np.ndarray),) |
def active_augment_learn(init_flag=None, train_data=None, num_initial=200, active_policy=uncertainty_sampling, augment_method=lf_augment, num_query=5, num_sample=[100, 100, 100, 100, 100], augment_rate=0.2, augment_decay=1, hyper_alpha=8, alpha_decay=1, Epochs=10, score_limit_low=0, score_limit_upper=500, fit_only_new_... |
class GPTJLoraInt8(CausalLoraInt8Model):
config_name: str = 'gptj_lora_int8'
def __init__(self, weights_path: Optional[str]=None):
super().__init__(GPTJLoraInt8Engine.config_name, weights_path) |
(scope='module')
def source_2bin_2channel():
with open('validation/data/2bin_2channel_example1.json', encoding='utf-8') as read_json:
return json.load(read_json) |
.parametrize('time_threshold, user_answer, item_answer', [(datetime.strptime('06-01-2020', '%d-%m-%Y'), [[1, 1, 1, 1, 1, 3, 3, 3, 3, 3], [2, 2, 2, 2, 2]], [[1, 2, 3, 4, 5, 1, 5, 3, 1, 2], [1, 2, 3, 9, 10]])])
.parametrize('dataset_type', [pytest.param('spark_dataframe_test', marks=pytest.mark.spark), pytest.param('pand... |
class FileSystemLoader(BaseLoader):
def __init__(self, searchpath, encoding='utf-8', followlinks=False):
if ((not isinstance(searchpath, abc.Iterable)) or isinstance(searchpath, string_types)):
searchpath = [searchpath]
self.searchpath = [fspath(p) for p in searchpath]
self.encod... |
def cat(g, tensor_list, dim, scale=None, zero_point=None):
tensors = sym_help._unpack_list(tensor_list)
input = tensors[0]
if (input not in sym_help._quantized_ops):
from torch.onnx.symbolic_opset9 import cat
return cat(g, tensor_list, dim)
dim = sym_help._parse_arg(dim, 'i')
kwargs ... |
def resnet50_inspecs_params_with_broadcast():
inspecs = []
u = I.UniformInitializer((0.5, 1.0))
inspecs.append([Inspec((5, 1024, 14, 14), u), Inspec((1, 1024, 1, 1), u)])
inspecs.append([Inspec((5, 1024, 14, 14), u), Inspec((1, 1024, 14, 14), u)])
inspecs.append([Inspec((5, 112, 112, 64), u), Inspec... |
_start_docstrings('\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ', REGNET_START_DOCSTRING)
class TFRegNetForImageClassification(TFRegNetPreTrainedModel, TFSequenceClassificationLoss):
def __init__(self, config: RegNetConfig,... |
def _extract_tarfiles(data_dir):
path = os.path.join(data_dir, 'features')
if (not os.path.isdir(path)):
os.mkdir(path)
feature_tar_files = open(os.path.join(data_dir, 'tar_files.txt')).read().strip().split('\n')
feature_tar_files = [os.path.join(data_dir, s) for s in feature_tar_files]
for ... |
def add_noise(word, probability):
word = remove_letters(word, (probability / 3))
word = add_letters(word, (probability / 3))
return word |
def produceImgAndLabel():
root_path = '/home/lmin/data/PennFudanPed/'
imgpath = sorted(glob(os.path.join(root_path, 'PNGImages/*.png')))
txtpath = sorted(glob(os.path.join(root_path, 'PedMasks/*.png')))
train_seg_txt = open(((root_path + 'train') + '_ins.txt'), 'a')
val_seg_txt = open(((root_path + ... |
def get_fields(data_type, n_src_features, n_tgt_features):
if (data_type == 'text'):
return TextDataset.get_fields(n_src_features, n_tgt_features)
elif (data_type == 'img'):
return ImageDataset.get_fields(n_src_features, n_tgt_features)
elif (data_type == 'audio'):
return AudioDatase... |
_with_pre_post_option('clean_arguments', pre=clean_polys_pre, default=True)
_with_pre_post_option('easy_linear_polynomials', pre=easy_linear_polynomials_pre, default=True)
_with_pre_post_option('result_to_list', post=result_to_list_post, default=True)
_heuristic(interpolation_gb_heuristic)
_with_pre_post_option('invert... |
class XGLMTokenizerFast(metaclass=DummyObject):
_backends = ['tokenizers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tokenizers']) |
def make_selectors(opt, kb_dict):
selectors = {}
input_size = (opt.rnn_size + (6 * opt.kb_embed_size))
selectors['enc'] = nn.GRU(input_size=opt.rnn_size, hidden_size=opt.kb_embed_size, bias=True, bidirectional=True)
selectors['dec'] = nn.Sequential(nn.Linear((11 * opt.rnn_size), opt.rnn_size), nn.Tanh()... |
class _MLPVectorProjector(nn.Module):
def __init__(self, input_hidden_size: int, lm_hidden_size: int, num_layers: int, width: int):
super(_MLPVectorProjector, self).__init__()
self.mlps = nn.ModuleList()
for _ in range(width):
mlp = [nn.Linear(input_hidden_size, lm_hidden_size)]
... |
class RoBERTaConfig(LMConfig):
def __init__(self, args=None):
super(RoBERTaConfig, self).__init__(args)
self.model = 'RoBerta'
self._post_init(args)
para_prefix = {**LMConfig.para_prefix}
args_to_parse = list(para_prefix.keys())
meta_data = {'RoBerta': SN(hf_model='roberta-base',... |
def add_vignette_node_group() -> bpy.types.NodeGroup:
group = bpy.data.node_groups.new(type='CompositorNodeTree', name='Vignette')
input_node = group.nodes.new('NodeGroupInput')
group.inputs.new('NodeSocketColor', 'Image')
group.inputs.new('NodeSocketFloat', 'Amount')
group.inputs['Amount'].default_... |
def _make_time_sift_events(prev_time, post_time):
time_interval = int(round(((post_time - prev_time) * 100)))
results = []
while (time_interval >= RANGE_TIME_SHIFT):
results.append(Event(event_type='time_shift', value=(RANGE_TIME_SHIFT - 1)))
time_interval -= RANGE_TIME_SHIFT
if (time_in... |
def _seg_12():
return [(3113, 'X'), (3114, 'V'), (3130, 'X'), (3133, 'V'), (3141, 'X'), (3142, 'V'), (3145, 'X'), (3146, 'V'), (3150, 'X'), (3157, 'V'), (3159, 'X'), (3160, 'V'), (3163, 'X'), (3168, 'V'), (3172, 'X'), (3174, 'V'), (3184, 'X'), (3191, 'V'), (3213, 'X'), (3214, 'V'), (3217, 'X'), (3218, 'V'), (3241, ... |
def createDict(word_freqs):
words = [k for k in word_freqs.keys()]
freqs = [v for v in word_freqs.values()]
sorted_idx = np.argsort(freqs)
sorted_words = [words[ii] for ii in sorted_idx[::(- 1)]]
_GO = '_GO'
EOS = '_EOS'
UNK = '_UNK'
PAD = '_PAD'
SEP0 = '_SEP0'
SEP1 = '_SEP1'
... |
class TestOptions(object):
def __init__(self):
self.parser = argparse.ArgumentParser()
self.initialized = False
def initialize(self):
self.parser.add_argument('--name', type=str, default='experiment_name', help='name of the experiment. It decides where to store samples and models')
... |
(config_path='control_pcgrl/configs', config_name='pod')
def main(cfg: PoDConfig):
cfg = validate_config(cfg)
if (cfg is False):
print('Invalid config!')
return
traj_dir = os.path.join(cfg.log_dir, 'repair-paths')
register_env('pcgrl', make_env)
model_cls = CustomFeedForwardModel
... |
def setup_test_file():
val = b'a\x00string'
(fd, fname) = mkstemp()
with os.fdopen(fd, 'wb') as fs:
fs.write(val)
with open(fname, 'rb') as fs:
gs = BytesIO(val)
cs = cStringIO(val)
(yield (fs, gs, cs))
os.unlink(fname) |
def test_download_7z_file(mocker, mock_download_from_remote, mock_un7z):
mock_download_from_remote.return_value = 'foo'
download_utils.download_7z_file('a', 'b', False, False)
mock_download_from_remote.assert_called_once_with('a', 'b', False)
mock_un7z.assert_called_once_with('foo', cleanup=False)
_... |
def get_image(image_path, is_grayscale=False):
image = imread(image_path, is_grayscale)
return transform(image) |
def register_Ns3CallbackImpl__Void_Ns3DataRate_Ns3DataRate_Ns3Mac48Address_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImpl< void, ns3::DataRate, ns3::DataRate, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::e... |
class Pipeline(object):
def __init__(self, convert_token=None):
if (convert_token is None):
self.convert_token = Pipeline.identity
elif callable(convert_token):
self.convert_token = convert_token
else:
raise ValueError('Pipeline input convert_token {} is n... |
class MBartTokenizer(XLMRobertaTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
prefix_tokens: List[int] = []
suffix_tokens: List[int] = []
def __init__(self, *args, tokenizer_... |
def get_models_status():
ner_status = subprocess.run(['docker', 'inspect', '-f', '{{.State.Running}}', 'myner'], capture_output=True, text=True).stdout.strip('\n')
intent_status = subprocess.run(['docker', 'inspect', '-f', '{{.State.Running}}', 'myintent'], capture_output=True, text=True).stdout.strip('\n')
... |
class ChangeFinalWeightQCAttrTest(BaseKerasFeatureNetworkTest):
def __init__(self, unit_test):
super().__init__(unit_test, experimental_exporter=True)
def get_debug_config(self):
return DebugConfig(network_editor=[EditRule(filter=NodeTypeFilter(layers.Conv2D), action=ChangeFinalWeightsQuantConfi... |
def Inception(inputs, units=8, strides=1):
x1 = Conv2D(units, 5, padding='same', activation='relu', strides=strides)(inputs)
x2 = Conv2D(units, 3, padding='same', activation='relu', strides=strides)(inputs)
x3 = Conv2D(units, 1, padding='same', activation='relu', strides=strides)(inputs)
outputs = Conca... |
def init_seed(seed):
torch.cuda.manual_seed_all(seed)
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = True |
class EdgeResidual(BaseModule):
def __init__(self, in_channels, out_channels, mid_channels, kernel_size=3, stride=1, se_cfg=None, with_residual=True, conv_cfg=None, norm_cfg=dict(type='BN'), act_cfg=dict(type='ReLU'), drop_path_rate=0.0, with_cp=False, init_cfg=None, **kwargs):
super(EdgeResidual, self).__i... |
class TFXLNetModelTest(TFCommonTestCases.TFCommonModelTester):
all_model_classes = ((TFXLNetModel, TFXLNetLMHeadModel, TFXLNetForSequenceClassification, TFXLNetForQuestionAnsweringSimple) if is_tf_available() else ())
test_pruning = False
class TFXLNetModelTester(object):
def __init__(self, parent, ... |
class DynamicBaselineConfig(DetectorConfig):
_default_trends = ['weekly', 'daily']
def __init__(self, fixed_period: Tuple[(str, str)]=None, train_window: str=None, wind_sz: str='1h', trends: List[str]=None, **kwargs):
super().__init__(**kwargs)
self.trends = (self._default_trends if (trends is N... |
class CtcCriterionConfig(FairseqDataclass):
zero_infinity: bool = field(default=False, metadata={'help': 'zero inf loss when source length <= target length'})
sentence_avg: bool = II('optimization.sentence_avg')
post_process: str = field(default='letter', metadata={'help': 'how to post process predictions i... |
_task('translation_multi_simple_epoch')
class TranslationMultiSimpleEpochTask(LegacyFairseqTask):
def add_args(parser):
parser.add_argument('-s', '--source-lang', default=None, metavar='SRC', help='inference source language')
parser.add_argument('-t', '--target-lang', default=None, metavar='TARGET',... |
class ConvolutionBranch(nn.Module):
def __init__(self, input_size, linear_units=3072, kernel_size=31, activation=nn.GELU, gate_activation=nn.Identity, dropout=0.0, use_linear_after_conv=False):
super().__init__()
self.pre_channel_proj = nn.Linear(input_size, linear_units)
self.post_channel_p... |
def conditional_bilinear_classifier(inputs1, inputs2, n_classes, probs, keep_prob, add_bias1=True, add_bias2=True):
input_shape = tf.shape(inputs1)
batch_size = input_shape[0]
bucket_size = input_shape[1]
input_size = inputs1.get_shape().as_list()[(- 1)]
input_shape_to_set = [tf.Dimension(None), tf.... |
class Classifier_Module(nn.Module):
def __init__(self, dilation_series, padding_series, num_classes):
super(Classifier_Module, self).__init__()
self.conv2d_list = nn.ModuleList()
for (dilation, padding) in zip(dilation_series, padding_series):
self.conv2d_list.append(nn.Conv2d(20... |
def run(seed):
tf.reset_default_graph()
dataset = uci_woval(args.dataset, seed=seed)
(train_x, test_x, train_y, test_y) = (dataset.x_train, dataset.x_test, dataset.y_train, dataset.y_test)
std_y_train = dataset.std_y_train[0]
(N, input_dim) = train_x.shape
lower_ap = np.minimum(np.min(train_x), ... |
def affiliation_partition(Is=[(1, 1.5), (2, 5), (5, 6), (8, 9)], E_gt=[(1, 2.5), (2.5, 4.5), (4.5, 10)]):
out = ([None] * len(E_gt))
for j in range(len(E_gt)):
E_gt_j = E_gt[j]
discarded_idx_before = [(I[1] < E_gt_j[0]) for I in Is]
discarded_idx_after = [(I[0] > E_gt_j[1]) for I in Is]
... |
def clip_loss(similarity: tf.Tensor) -> tf.Tensor:
caption_loss = contrastive_loss(similarity)
image_loss = contrastive_loss(tf.transpose(similarity))
return ((caption_loss + image_loss) / 2.0) |
def get_proposed_method(selector):
_added = _get_proposed(['causal-da'], selector)
_cv = (cv_group + ['method'])
return VirtualValidation(_added).fit(_cv, [('min_selector', {'larger_is_better': False})])[(((_cv + ['target_c']) + ['test_metric']) + ['sacred_run_id'])] |
def main():
args = get_arguments()
start = time.time()
logger = setup_logger()
writer = SummaryWriter(args.model_save_path)
logger.info(json.dumps(vars(args), indent=1))
logger.info('Setting model...')
model = DRSN()
model.init(args.init_model_path, 'yvos_train')
model.train()
mo... |
class TNEANetMPNodeI(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
_snap.TNEANetMPNodeI_swiginit(self, _snap.new_TNEANetMPNodeI(*args))
def Next(self):
return _snap.TNE... |
class MetricGroup():
def __init__(self, metric_kwarg_list):
self.metrics = [dnnlib.util.call_func_by_name(**kwargs) for kwargs in metric_kwarg_list]
def run(self, *args, **kwargs):
for metric in self.metrics:
metric.run(*args, **kwargs)
def get_result_str(self):
return ' ... |
def num_cpus_used_by_tokenizer(tokenizer) -> int:
if getattr(tokenizer, 'is_fast', False):
if (os.getenv('TOKENIZERS_PARALLELISM', 'true').lower() in _HF_TOKENIZER_OFF_VALUES):
return 1
else:
return min(max(1, (logical_cpu_core_count() - 2)), 8)
else:
return 1 |
def register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImpl< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty... |
class DataProcessor():
def __init__(self, path):
self.data = self.load_data(path)
def load_data(self, path):
multi_label_data = {}
with open(path) as f:
data = json.load(f)
for dial in data:
dialog_history = ''
for (idx, turn) in en... |
class DoxyParameterItem(DoxyMember):
def _parse(self):
if self._parsed:
return
super(DoxyParameterItem, self)._parse()
names = []
for nl in self._parse_data.parameternamelist:
for pn in nl.parametername:
names.append(description(pn))
se... |
def dataio_prep(hparams):
language_encoder = sb.dataio.encoder.CategoricalEncoder()
.data_pipeline.takes('wav')
.data_pipeline.provides('sig')
def audio_pipeline(wav):
(sig, _) = torchaudio.load(wav)
sig = sig.transpose(0, 1).squeeze(1)
return sig
.data_pipeline.takes('langua... |
('parsing', 'ael', AELParams)
class AEL(ParsingAlgo):
def __init__(self, params: AELParams):
self.rex = params.rex
self.minEventCount = params.minEventCount
self.merge_percent = params.merge_percent
self.df_log = None
self.logname = None
self.merged_events = []
... |
class DynamicalSystem_affine(SchemeMorphism_polynomial_affine_space, DynamicalSystem):
def __classcall_private__(cls, morphism_or_polys, domain=None):
if isinstance(morphism_or_polys, SchemeMorphism_polynomial):
morphism = morphism_or_polys
R = morphism.base_ring()
polys ... |
def load_table(run, desired_table_name):
desired_file = [p for p in run.files() if (desired_table_name in p.name)][0]
data = ''
for line in urllib.request.urlopen(desired_file.direct_url):
data += line.decode('utf-8')
return json.loads(data) |
class TraditionalLexer(Lexer):
def __init__(self, conf):
terminals = list(conf.tokens)
assert all((isinstance(t, TerminalDef) for t in terminals)), terminals
self.re = conf.re_module
if (not conf.skip_validation):
for t in terminals:
try:
... |
class ModelArguments():
model_name_or_path: str = field(metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'})
config_name: Optional[str] = field(default=None, metadata={'help': 'Pretrained config name or path if not the same as model_name'})
tokenizer_name: Optional[s... |
def visualization_experiments(num_experiments: Optional[int]=None) -> None:
print('RUNNING `visualization_experiments`')
if (num_experiments is None):
num_experiments = NUM_VISUALIZATION_EXPERIMENTS
for heuristic in hans.DEFAULT_HANS_EVAL_HEURISTICS:
visualization.main(train_task_name='hans'... |
def _try_run(model_name, bench_fn, bench_kwargs, initial_batch_size, no_batch_size_retry=False):
batch_size = initial_batch_size
results = dict()
error_str = 'Unknown'
while batch_size:
try:
torch.cuda.empty_cache()
bench = bench_fn(model_name=model_name, batch_size=batch... |
def test_sdca_hinge_multiclass(train_data):
(X, y) = train_data
clf = SDCAClassifier(alpha=0.01, max_iter=100, loss='hinge', random_state=0)
clf.fit(X, y)
np.testing.assert_almost_equal(clf.score(X, y), 0.933, 3) |
class RepPAN(nn.Module):
def __init__(self, subtype='yolov6_s', in_channels=[256, 512, 1024], mid_channels=[128, 128, 256], out_channels=[128, 256, 512], layers=[12, 12, 12, 12], depth_mul=1.0, width_mul=1.0):
super().__init__()
self.subtype = subtype
assert (in_channels is not None)
... |
def main(args):
outfile = args.outfile
download_tf_params()
model = Inception()
set_tf_params(model)
print('Saving ', outfile, '...')
serializers.save_hdf5(outfile, model) |
class FedAvgM_Selection(PrivilegedAggregationFunction):
def call(self, local_tensors, tensor_db, tensor_name, fl_round, tags):
tensor_db.store(tensor_name='momentum', nparray=0.9, overwrite=False)
tensor_db.store(tensor_name='aggregator_lr', nparray=1.0, overwrite=False)
if (fl_round == 0):
... |
def make_nested_sdfg():
sdfg = dace.SDFG('vol_propagation_nested')
assign_loop_bound = sdfg.add_state('assign')
guard_state = sdfg.add_state('guard')
loop_state = sdfg.add_state('for')
end_state = sdfg.add_state('endfor')
sdfg.add_edge(assign_loop_bound, guard_state, InterstateEdge(assignments={... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.