code stringlengths 101 5.91M |
|---|
def TrainSVM(Xtrain, ytrain):
SVM_GRID_PARAMS = [{'kernel': ['rbf'], 'gamma': [0.001, 0.01, 0.1, 1], 'C': [0.1, 1, 10, 100, 1000]}, {'kernel': ['linear'], 'C': [0.1, 1, 10, 100, 1000]}, {'kernel': ['poly'], 'degree': [3], 'gamma': [0.1, 0.01, 0.001]}]
class_weight = 'balanced'
clf = sklearn.svm.SVC(class_we... |
def eval_noise_wer(trans_path, result_path):
whisper_trans = fileList(trans_path)
truth_path = '/data/sls/scratch/yuangong/whisper-a/src/noisy_exp/ground_truth_trans/'
truth_trans = fileList(truth_path)
print(len(whisper_trans), len(truth_trans))
def preprocess_text(cur_trans):
cur_trans = j... |
def get_frame_shift(data_folder):
process = run(['utils/data/get_frame_shift.sh', data_folder])
return float(process.stdout.decode('utf-8')) |
class SigmoidActivationMixin():
def init_activation(self, upperbound=1.0, eps=0.0001, **kwargs):
self.eps = eps
self._activation_func = nn.Sigmoid()
self._log_activation_func = nn.LogSigmoid()
self.upperbound = torch.tensor(upperbound)
self.activation_func = (lambda x: (self.... |
class FlaxKarrasVeScheduler(FlaxSchedulerMixin, ConfigMixin):
def has_state(self):
return True
_to_config
def __init__(self, sigma_min: float=0.02, sigma_max: float=100, s_noise: float=1.007, s_churn: float=80, s_min: float=0.05, s_max: float=50):
pass
def create_state(self):
ret... |
def _get_plugin():
fn = os.path.join(os.path.dirname(__file__), 'tf_all.cu')
return plugin_loader.get_plugin(fn, extra_nvcc_options=(_get_gl_opts() + ['-DNVDR_TENSORFLOW'])) |
def get_dataset(args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate: bool=False, cache_dir: Optional[str]=None):
def _dataset(file_path, ref_path=None):
if args.line_by_line:
if (ref_path is not None):
if ((not args.whole_word_mask) or (not args.mlm)):
... |
def switch_interpolation(transforms: Callable[([T], Union[(T, Tensor)])], *, interp: str):
assert (interp in ('bilinear', 'nearest')), interp
previous_inters = OrderedDict()
transforms = get_transform(transforms)
interpolation = get_interpolation(interp)
for (id_, t) in enumerate(transforms):
... |
class ResNet18(nn.Module):
def __init__(self, num_classes, pretrained=True, include_top=False, freeze=True):
super().__init__()
backbone = vision.resnet18(pretrained=pretrained, include_top=include_top, freeze=freeze)
output_size = backbone.get_output_size()
head = nn.Linear(output_s... |
class MILFeatures():
uq = None
def __init__(self, model: Optional[Union[(str, 'torch.nn.Module')]], bags: Union[(np.ndarray, List[str], str)], *, slides: Optional[list]=None, config: Optional[_TrainerConfig]=None, dataset: Optional['sf.Dataset']=None, attention_pooling: Optional[str]='avg', device: Optional[Any... |
def build_fake_yaml():
fake_yaml = "\n model:\n name: gradient_sensitivity_prune\n framework: pytorch\n pruning:\n approach:\n weight_compression:\n start_epoch: 0\n end_epoch: 1\n pruners:\n - !Pruner\n ... |
def set_default_style(color_scheme='dark', spacing=9, indent=23, scrollbar=27):
s = imgui.get_style()
s.window_padding = [spacing, spacing]
s.item_spacing = [spacing, spacing]
s.item_inner_spacing = [spacing, spacing]
s.columns_min_spacing = spacing
s.indent_spacing = indent
s.scrollbar_size... |
def is_flaky(max_attempts: int=5, wait_before_retry: Optional[float]=None, description: Optional[str]=None):
def decorator(test_func_ref):
(test_func_ref)
def wrapper(*args, **kwargs):
retry_count = 1
while (retry_count < max_attempts):
try:
... |
def dis_down_noins(images, kernel_size, stride, n_scale, ch, name):
backpack = images[0]
for i in range(n_scale):
if (i == (n_scale - 1)):
images[i] = num_steps_noins(backpack, ch, kernel_size, stride, n_scale, (name + str(i)))
else:
images[i] = one_step_noins(images[(i +... |
class ExplanationJSONEncoder(JSONEncoder):
def default(self, o):
from interpret.newapi.explanation import Explanation
from interpret.newapi.component import Component
if isinstance(o, np.ndarray):
return {'_type': 'array', 'value': o.tolist()}
elif isinstance(o, Explanati... |
class XLMTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, vocab_file, merges_file, unk_token='<unk>', bos_token='<s>', sep_token='</s>', pad_toke... |
def article(word, function=INDEFINITE, gender=MALE, role=SUBJECT):
return (((function == DEFINITE) and definite_article(word, gender, role)) or indefinite_article(word, gender, role)) |
def define_G(opt):
opt_net = opt['network_G']
which_model = opt_net['which_model_G']
if (which_model == 'MSRResNet'):
netG = SRResNet_arch.MSRResNet(in_nc=opt_net['in_nc'], out_nc=opt_net['out_nc'], nf=opt_net['nf'], nb=opt_net['nb'], upscale=opt_net['scale'])
elif (which_model == 'RRDBNet'):
... |
def AddLstmLayer(config_lines, name, input, cell_dim, recurrent_projection_dim=0, non_recurrent_projection_dim=0, clipping_threshold=30.0, zeroing_threshold=15.0, zeroing_interval=20, ng_per_element_scale_options='', ng_affine_options='', lstm_delay=(- 1), self_repair_scale_nonlinearity=None, max_change_per_component=0... |
def HPathExists(filepath: str):
if (not filepath.startswith('hdfs://')):
return os.path.exists(filepath)
pass |
def process_rot(rotation):
if (rotation[0] > 0):
rotation[0] = (np.pi - rotation[0])
else:
rotation[0] = ((- np.pi) - rotation[0])
if (rotation[2] > 0):
rotation[2] = (np.pi - rotation[2])
else:
rotation[2] = ((- np.pi) - rotation[2])
return np.array([(- rotation[2]),... |
def read_requirements(file: str) -> list[str]:
return [line for line in open(file) if (not (line.startswith('#') or line.startswith('--')))] |
_HEADS_REGISTRY.register()
class AttributeStandardROIHeads(AttributeROIHeads, StandardROIHeads):
def __init__(self, cfg, input_shape):
super(StandardROIHeads, self).__init__(cfg, input_shape)
self._init_box_head(cfg, input_shape)
self._init_mask_head(cfg, input_shape)
self._init_keyp... |
def test_for_loop_binding():
run_cell('a = 0')
run_cell('b = 1')
run_cell('c = 2')
run_cell('lst = [a, b, c]')
run_cell('\n for i in lst:\n pass\n ')
run_cell('a = 3')
run_cell('logging.info(i)')
assert_false_positive('`i` should not depend on `a` at end of for l... |
class IICTrainer(_FeatureExtractor, SemiTrainer):
def _init(self):
super(IICTrainer, self)._init()
config = deepcopy(self._config['IICRegParameters'])
self._mi_estimator_array = IICEstimatorArray()
self._mi_estimator_array.add_encoder_interface(feature_names=self.feature_positions, *... |
class PointNetCls(nn.Module):
def __init__(self, c=3, k=40, dropout=0.3, sync_bn=False):
super(PointNetCls, self).__init__()
self.feat = PointNetFeat(c, global_feat=True)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, k)
self.... |
_module()
class OBBTwoStageDetector(OBBBaseDetector, RotateAugRPNTestMixin):
def __init__(self, backbone, neck=None, rpn_head=None, roi_head=None, train_cfg=None, test_cfg=None, pretrained=None):
super(OBBTwoStageDetector, self).__init__()
self.backbone = build_backbone(backbone)
if (neck is... |
def cosine_similarity(x1, x2=None, eps=1e-08):
x2 = (x1 if (x2 is None) else x2)
w1 = x1.norm(p=2, dim=1, keepdim=True)
w2 = (w1 if (x2 is x1) else x2.norm(p=2, dim=1, keepdim=True))
sim = (torch.mm(x1, x2.t()) / (w1 * w2.t()).clamp(min=eps))
return sim |
class Results(list):
def __init__(self, source=None, query=None, type=SEARCH, total=0):
self.source = source
self.query = query
self.type = type
self.total = total |
class FancyUnbiasedRiskEstimatorCut1(RiskEstimator):
def __init__(self, loss, dataset, *args):
super().__init__(loss)
self.N = len(dataset.test_idxs)
def estimate(self, predictions, observed, acq_weights):
l_i = self.loss(predictions, observed)
N = self.N
M = len(predicti... |
_criterion('speech_and_text_translation', dataclass=SpeechAndTextTranslationCriterionConfig)
class SpeechAndTextTranslationCriterion(LabelSmoothedCrossEntropyCriterion):
def __init__(self, task, sentence_avg, label_smoothing, ignore_prefix_size=0, report_accuracy=False, mt_finetune=False):
super().__init__(... |
def get_torch_version():
try:
torch_version = torch.__version__.split('+')[0]
except ValueError as e:
assert False, 'Got an unknown version of torch: {}'.format(e)
version = Version(torch_version)
return version |
def build_one_cycle_optimizer(model, optimizer_config):
if optimizer_config.fixed_wd:
optimizer_func = partial(torch.optim.Adam, betas=(0.9, 0.99), amsgrad=optimizer_config.amsgrad)
else:
optimizer_func = partial(torch.optim.Adam, amsgrad=optimizer_cfg.amsgrad)
optimizer = OptimWrapper.creat... |
def init_multiprocessing(rank, sync_device):
global _rank, _sync_device
assert (not _sync_called)
_rank = rank
_sync_device = sync_device |
def style_transfer(sess, dataloader):
time_list = []
output_name = add_import_to_name(sess, 'transformer/expand/conv3/conv/Sigmoid:0', 3)
style_name = add_import_to_name(sess, 'style_input:0', 3)
content_name = add_import_to_name(sess, 'content_input:0', 3)
stylized_images = sess.graph.get_tensor_by... |
def build_loaders(train_dataset, val_dataset):
train_loader = DataLoader(train_dataset, batch_size=5, shuffle=True, num_workers=multiprocessing.cpu_count(), pin_memory=torch.cuda.is_available())
val_loader = DataLoader(val_dataset, batch_size=5, shuffle=False, num_workers=multiprocessing.cpu_count(), pin_memory... |
def replace_from_right(string: str, old: str, new: str, count: int=(- 1)):
assert isinstance(string, str)
assert isinstance(old, str)
assert isinstance(new, str)
assert isinstance(count, int)
string = string.rsplit(old, count)
return new.join(string) |
.parametrize('device_type', ['cpu', pytest.param('cuda:0', marks=pytest.mark.skipif((not torch.cuda.is_available()), reason='requires CUDA support'))])
def test_multiscale_deformable_attention(device_type):
with pytest.raises(ValueError):
MultiScaleDeformableAttention(embed_dims=256, num_heads=7)
device... |
def conv_bn_relu(in_channels, out_channels, kernel_size, stride, padding, groups, dilation=1):
if (padding is None):
padding = (kernel_size // 2)
result = conv_bn(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, dilation=dilation... |
def _parse_args():
parser = ArgumentParser()
parser.add_argument('--cluster_mode', type=str, default='local', help='The cluster mode, such as local, yarn, standalone or spark-submit.')
parser.add_argument('--master', type=str, default=None, help='The master url, only used when cluster mode is standalone.')
... |
def download_model(url, model_name, retry_times=5):
if os.path.isfile(model_name):
print(f'{model_name} exists, skip download')
return True
print('download model...')
retries = 0
while (retries < retry_times):
try:
request.urlretrieve(url, model_name, schedule)
... |
class RandomIntensityScale(object):
def __init__(self, min: float=0.9, max: float=1.1):
super().__init__()
self.min = min
self.max = max
def __call__(self, img_and_mask: Tuple[(np.ndarray, np.ndarray, np.ndarray)]) -> Tuple[(np.ndarray, np.ndarray, np.ndarray)]:
(modalities, _, m... |
def get_padding_value(padding, kernel_size, **kwargs) -> Tuple[(Tuple, bool)]:
dynamic = False
if isinstance(padding, str):
padding = padding.lower()
if (padding == 'same'):
if is_static_pad(kernel_size, **kwargs):
padding = get_padding(kernel_size, **kwargs)
... |
def pack_trackingnet_results(tracker_name, param_name, run_id=None, output_name=None):
if (output_name is None):
if (run_id is None):
output_name = '{}_{}'.format(tracker_name, param_name)
else:
output_name = '{}_{}_{:03d}'.format(tracker_name, param_name, run_id)
output_... |
def main(_):
calib_dataset = COCORecordDataset(root=args.dataset_location, filter=LabelBalanceCOCORecordFilter(size=1))
calib_dataloader = DataLoader(framework='tensorflow', dataset=calib_dataset, batch_size=1)
if args.tune:
from neural_compressor import quantization
from neural_compressor.c... |
def retrieve_data(data, key):
if isinstance(data, dict):
identifier = '_{}'.format(key)
out_data = {k.replace(identifier, ''): v for (k, v) in data.items() if (identifier in k)}
return out_data |
def mixed_spec(singly_nested_spec: specs.Spec, not_jumanji_type_spec: specs.Spec) -> specs.Spec:
return specs.Spec(namedtuple('mixed_type', ['singly_nested', 'not_jumanji_type']), 'MixedSpec', singly_nested=singly_nested_spec, not_jumanji_type=not_jumanji_type_spec) |
def evaluate_levircd(self, test_dataloader, config=None):
self.model.eval()
device = (torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu'))
metric_op = er.metric.PixelMetric(2, self.model_dir, logger=self.logger)
with torch.no_grad():
for (img, ret_gt) in tqdm(test_dataload... |
_start_docstrings('The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.', POOLFORMER_START_DOCSTRING)
class PoolFormerModel(PoolFormerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.encoder = Poo... |
def recreate_local_parser_cache():
import iheartla.la_parser.parser
PM = iheartla.la_parser.parser._parser_manager
print('## Clearing the cache dir:', PM.cache_dir)
shutil.rmtree(PM.cache_dir)
Path(PM.cache_dir).mkdir()
la_local_parsers = (PM.grammar_dir.parent / 'la_local_parsers')
print('#... |
def test_construct_arguments_does_not_overwrite_args_and_kwargs():
s = Signature(bariza)
(args, kwargs) = s.construct_arguments([1, 2], {'c': 3}, {'a': 6, 'b': 6, 'c': 6})
assert (args == [1, 2])
assert (kwargs == {'c': 3}) |
class SaveWrapper(AbstractTrainerWrapper):
def __init__(self, *args, model_root_directory=None, saving_period=10000, **kwargs):
super().__init__(*args, **kwargs)
if (model_root_directory is None):
from ..configuration import configuration
model_root_directory = configuration.... |
class TFElectraForPreTraining(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def load_checkpoint(model, checkpoint_path, use_ema=False, strict=True):
state_dict = load_state_dict(checkpoint_path, use_ema)
model.load_state_dict(state_dict, strict=strict) |
def main():
args = get_args()
tgt_dir = pathlib.Path(args.out_dir)
tgt_dir.mkdir(exist_ok=True, parents=True)
(total_files, sufficiently_long) = (0, 0)
with open(args.prompts_description, 'r') as f:
description = json.loads(f.read())
for src_f in pathlib.Path(args.samples_dir).glob('*.wa... |
def get_scheduler(optimizer, n_iter_per_epoch, args):
if ('cosine' in args.lr_scheduler):
return WarmUpCosineAnnealingLR(optimizer=optimizer, warm_multiplier=args.warmup_multiplier, warm_duration=(args.warmup_epoch * n_iter_per_epoch), cos_duration=((args.epochs - args.warmup_epoch) * n_iter_per_epoch), eta... |
_registry.register_trainer(name='ddppo')
class DDPPOTrainer(PPOTrainer):
SHORT_ROLLOUT_THRESHOLD: float = 0.25
def __init__(self, config=None):
interrupted_state = load_interrupted_state()
if (interrupted_state is not None):
config = interrupted_state['config']
super().__init... |
def test_item_based_cf():
cf_based_similarity = ItemCFBasedSimilarity(data_file='../data/Sports_and_Outdoors_sample.txt', similarity_path='../data/item_cf_iuf_similarity.pkl', model_type='ItemCF_IUF')
print(cf_based_similarity.most_similar('2', top_k=4)) |
_TFIntersection.register('hard')
class TFHardIntersection(_TFIntersection):
def __call__(self, left: TFTBoxTensor, right: TFTBoxTensor) -> TFTBoxTensor:
return tf_hard_intersection(left, right) |
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName('Form')
Form.resize(1920, 1080)
self.add_brush_widgets(Form)
self.add_top_buttons(Form)
self.add_label_buttons(Form)
self.add_tool_buttons(Form)
self.add_checkbox_widgets(Form)
self.add... |
def merge_label(js1, js2, output_path):
total_label_cnt = 0
with open(js1, 'r', encoding='utf8') as fp:
data_file = json.load(fp)
data1 = data_file['data']
with open(js2, 'r', encoding='utf8') as fp:
data_file = json.load(fp)
data2 = data_file['data']
for (i, sample) in e... |
def main():
parser = ArgumentParser()
parser.add_argument('img_root', type=str, help='Image root path')
parser.add_argument('img_list', type=str, help='Image path list file')
parser.add_argument('config', type=str, help='Config file')
parser.add_argument('checkpoint', type=str, help='Checkpoint file... |
class LifeCycle(metaclass=ABCMeta):
def setup(self, cores_per_node):
import torch
torch.set_num_threads(cores_per_node)
def setup_torch_distribute(self, tcp_store_host, tcp_store_port, world_rank, world_size):
self._init_torch_ddp(tcp_store_host, tcp_store_port, world_rank, world_size)
... |
class TIMM(Backbone):
def __init__(self, base_name, out_levels, freeze_at=0, norm='FrozenBN', pretrained=False):
super().__init__()
out_indices = [(x - 1) for x in out_levels]
if (base_name in model_params):
self.base = create_timm_resnet(base_name, out_indices=out_indices, pretr... |
class Parameters():
def __init__(self, input_shape, batch_size=64, num_epochs=400, num_classes=10, alpha=1.0, num_blocks=2, max_num_training_samples=None, weight_regularizer=0.0001, dropout=0, use_bias=False, pretrained_model_path=None, max_value=None, activity_regularizer=None, signed_input=False, working_dir=None... |
def construct_placeholders(num_classes):
placeholders = {'labels': tf.placeholder(tf.float32, shape=(None, num_classes), name='labels'), 'batch': tf.placeholder(tf.int32, shape=None, name='batch1'), 'dropout': tf.placeholder_with_default(0.0, shape=(), name='dropout'), 'batch_size': tf.placeholder(tf.int32, name='b... |
class StopwatchMeter(object):
def __init__(self):
self.reset()
def start(self):
self.start_time = time.time()
def stop(self, n=1):
if (self.start_time is not None):
delta = (time.time() - self.start_time)
self.sum += delta
self.n += n
s... |
class SpeakerDiarization(base.Pipeline):
def __init__(self, config: (SpeakerDiarizationConfig | None)=None):
self._config = (SpeakerDiarizationConfig() if (config is None) else config)
msg = f'Latency should be in the range [{self._config.step}, {self._config.duration}]'
assert (self._config... |
class Scale(object):
def __init__(self, size):
self.size = size
def __call__(self, image):
image = self.changeScale(image, self.size)
return image
def changeScale(self, img, size, interpolation=Image.BILINEAR):
(ow, oh) = size
return img.resize((ow, oh), interpolation... |
def main():
args = parser.parse_args()
assert (args.dataset == 'imagenet')
args.num_classes = 1000
args.IMAGE_SIZE = 224
model = eval(args.model)(args)
(n_flops, n_params) = measure_model(model, args.IMAGE_SIZE, args.IMAGE_SIZE)
print(('FLOPs: %.2fM, Params: %.2fM' % ((n_flops / 1000000.0), ... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, multi_grid=1):
super(BasicBlock, self).__init__()
dilation = (dilation * multi_grid)
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=dilat... |
def euclidean_dist(x, y):
(m, n) = (x.size(0), y.size(0))
xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n)
yy = torch.pow(y, 2).sum(1, keepdim=True).expand(n, m).t()
dist = (xx + yy)
dist.addmm_(x, y.t(), beta=1, alpha=(- 2))
dist = dist.clamp(min=1e-12).sqrt()
return dist |
def clip_to_window(keypoints, window, scope=None):
with tf.name_scope(scope, 'ClipToWindow'):
(y, x) = tf.split(value=keypoints, num_or_size_splits=2, axis=2)
(win_y_min, win_x_min, win_y_max, win_x_max) = tf.unstack(window)
y = tf.maximum(tf.minimum(y, win_y_max), win_y_min)
x = tf.... |
def graph_resnet101_scheduled(min_num_epochs=0, max_num_epochs=400):
labels = ['Standard Trained Model 1', 'Standard Trained Model 2', 'Standard Trained Model 3', 'Standard Trained Model 4', 'Standard Trained Model 5', 'ASWT Model 1', 'ASWT Model 2']
xaxis = list(range(min_num_epochs, max_num_epochs))
curve... |
def check_regression_targets(y):
assert (y.ndim == 1)
if (y.dtype != dtype_t):
y = y.astype(dtype_t)
return y |
def test_quad_double_hyperbola(vrblvl=0):
par = 0.1
xtp = ['x^2 - (t - 0.5)^2 - 0.01;']
solx = (sqrt(((4 * (par ** 2)) + 1)) / 2)
print('\nvalue of the first start solution :', solx)
sol1 = make_solution(['x'], [solx])
print('the first start solution :\n', sol1)
sol2 = make_solution(['x'], [... |
def main():
parser = HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
(model_args, data_args, training_args) = parser.parse_args_into_dataclasses()
if (os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and (not training_args.over... |
_registry(pattern_type='EinsumwithArange')
class EinsumwithArange(Pattern):
def __call__(self, model):
pattern_mapping_config = {'EinsumwithArange': [{'patterns': {'in': [[(0, 'Shape'), (1, 'Arange'), (2, 'Einsum')]], 'out': [[(0, 'Range'), (1, 'Reshape'), (2, 'Matmul')]]}, 'search_mode': 'op_type', 'node_n... |
def select_relevant_portion(text):
paras = text.split('\n')
selected = []
done = False
for para in paras:
sents = sent_tokenize.tokenize(para)
for sent in sents:
words = nltk.word_tokenize(sent)
for word in words:
selected.append(word)
... |
def update_medoid_per_cluster(pairwise_distances, pairwise_distances_subset, labels, chosen_ids, cluster_member_ids, cluster_idx, margin_multiplier, margin_type):
def func_cond(iteration, scores_margin):
del scores_margin
return (iteration < num_candidates)
def func_body(iteration, scores_margin... |
def populate_defaults():
s = {}
for n in names:
v = default_model_settings.get(n, None)
if (v is None):
v = default_training_settings.get(n, None)
if (v is None):
v = default_feature_settings.get(n, None)
s[n] = v
return s |
class GwcDispProcessor(nn.Module):
def __init__(self, maxdisp=192, downsample=4, num_groups=40, use_concat_volume=True, concat_channels=12, *args, **kwargs):
super().__init__()
self.maxdisp = maxdisp
self.downsample = downsample
self.num_groups = num_groups
self.use_concat_vo... |
def _write_memory_from_list(shm: SharedMemory, files: List[Tuple[(str, WriteItem)]], planner: SavePlanner):
write_results = []
offset = 0
no_shard_data: Dict[(str, STORAGE_TYPES)] = {}
for (storage_key, write_item) in files:
data = planner.resolve_data(write_item)
if torch.is_tensor(data... |
_SCHEDULERS.register('CosineAnnealingLR')
def build_cosine_annealing_lr(cfg, optimizer):
assert isinstance(optimizer, Optimizer)
max_epoch = cfg.TRAIN.MAX_EPOCH
if cfg.LR_SCHEDULER.IS_WARMUP:
max_epoch -= cfg.LR_SCHEDULER.WARMUP.ITERATION
minimal_lr = cfg.LR_SCHEDULER.COSINE_ANNEALING_LR.MINIMAL... |
def compute_transformation_matrix(src_points, image_width, image_height):
dst_points = np.array([[0, 0], [image_width, 0], [image_width, image_height], [0, image_height]], dtype=np.float32)
return cv.getPerspectiveTransform(src_points, dst_points) |
def get_bn_layer(bn_type: str):
if bn_type.startswith('d'):
base_norm_class = get_bn_layer(bn_type[1:])
bn_class = {'1d': (lambda num_features, **kwargs: DualNormLayer(num_features, bn_class=base_norm_class['1d'], **kwargs)), '2d': (lambda num_features, **kwargs: DualNormLayer(num_features, bn_class... |
_BOX_PREDICTOR.register('FPNPredictor')
class FPNPredictor(nn.Module):
def __init__(self, cfg):
super(FPNPredictor, self).__init__()
num_classes = cfg.MODEL.ROI_BOX_HEAD.NUM_CLASSES
representation_size = cfg.MODEL.ROI_BOX_HEAD.MLP_HEAD_DIM
self.cls_score = nn.Linear(representation_si... |
class TrainingVAE(TrainingInterface):
def _batch_to_inputs(self, batch):
(_, _, pr_mat, x, c, dt_x) = batch
pr_mat = pr_mat.to(self.device).float()
x = x.to(self.device).long()
c = c.to(self.device).float()
dt_x = dt_x.to(self.device).float()
return (x, c, pr_mat, dt_... |
def convert(lst):
vocab = "what I 've come to realize about Afghanistan , and this is something that is often dismissed in the West".split()
dd = {(idx + 4): word for (idx, word) in enumerate(vocab)}
dd[0] = 'UNK'
dd[1] = 'PAD'
dd[2] = 'BOS'
dd[3] = 'EOS'
return ' '.join((dd[xx] for xx in ls... |
def set_global_seeds(i):
try:
import torch
except ImportError:
pass
else:
torch.manual_seed(i)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(i)
np.random.seed(i)
random.seed(i) |
def bbox2Coords(box):
assert (len(box) == 4)
x1 = int(round(box[0]))
y1 = int(round(box[1]))
x2 = int(round(box[2]))
y2 = int(round(box[3]))
return [x1, y1, x2, y1, x2, y2, x1, y2] |
def main():
args = get_parser().parse_args()
audio_sec = 0
decode_sec = 0
n_utt = 0
audio_durations = []
start_times = []
end_times = []
for x in glob.glob(os.path.join(args.log_dir, 'decode.*.log')):
with codecs.open(x, 'r', 'utf-8') as f:
for line in f:
... |
def SENet(model_params, input_tensor=None, input_shape=None, include_top=False, classes=1000, weights='imagenet', stride_size=2, init_filters=64, repetitions=None, **kwargs):
global backend, layers, models, keras_utils
(backend, layers, models, keras_utils) = get_submodules_from_kwargs(kwargs)
residual_bloc... |
class DeepModel(nn.Module):
def __init__(self, input_size, num_classes, config):
super().__init__()
if (config == 'resnet18'):
self.model = resnet18(num_classes=num_classes)
elif (config == 'resnet32grasp'):
self.model = resnet32_grasp(num_classes=num_classes)
... |
def gen_CustomizedNet():
import torch
import torch.nn as nn
class CustomizedNet(nn.Module):
def __init__(self, dropout, input_size, input_feature_num, hidden_dim, output_size):
super().__init__()
self.fc1 = nn.Linear((input_size * input_feature_num), hidden_dim)
s... |
def test_constaninit():
model = nn.Sequential(nn.Conv2d(3, 1, 3), nn.ReLU(), nn.Linear(1, 2))
func = ConstantInit(val=1, bias=2, layer='Conv2d')
func(model)
assert torch.equal(model[0].weight, torch.full(model[0].weight.shape, 1.0))
assert torch.equal(model[0].bias, torch.full(model[0].bias.shape, 2... |
def test_sparsify():
target = iris.target_names[iris.target]
clf = LogisticRegression(random_state=0).fit(iris.data, target)
pred_d_d = clf.decision_function(iris.data)
clf.sparsify()
assert sp.issparse(clf.coef_)
pred_s_d = clf.decision_function(iris.data)
sp_data = sp.coo_matrix(iris.data)... |
_model_architecture('linformer_roberta', 'linformer_roberta_base')
def linformer_roberta_base_architecture(args):
base_architecture(args) |
class SemanticStableDiffusionPipeline(metaclass=DummyObject):
_backends = ['torch', 'transformers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch', 'transformers'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['torch', 'transformers'])
def from_pr... |
class DefaultDataset(data.Dataset):
def __init__(self, root, transform=None):
self.samples = listdir(root)
self.samples.sort()
self.transform = transform
self.targets = None
def __getitem__(self, index):
fname = self.samples[index]
img = Image.open(fname).convert(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.