code stringlengths 101 5.91M |
|---|
class MPClassFuncOnDemand():
def __init__(self, class_handle, class_func_name, **class_kwargs):
self.class_handle = class_handle
self.class_func_name = class_func_name
self.class_kwargs = class_kwargs
self.class_func = None
self.s2c = multiprocessing.Queue()
self.c2s ... |
def nondefault_trainer_args(opt):
parser = argparse.ArgumentParser()
parser = Trainer.add_argparse_args(parser)
args = parser.parse_args([])
return sorted((k for k in vars(args) if (getattr(opt, k) != getattr(args, k)))) |
class FixedBernoulli(torch.distributions.Bernoulli):
def log_probs(self, actions):
return super.log_prob(actions).view(actions.size(0), (- 1)).sum((- 1)).unsqueeze((- 1))
def entropy(self):
return super().entropy().sum((- 1))
def mode(self):
return torch.gt(self.probs, 0.5).float() |
class ModelParallelTransformerDecoder(TransformerDecoder):
def build_decoder_layer(self, args, no_encoder_attn=False):
return ModelParallelTransformerDecoderLayer(args, no_encoder_attn)
def output_layer(self, features, **kwargs):
if (not self.share_input_output_embed):
raise NotImple... |
def closure_sgd():
global i, out_avg, sgd_out, sgd_expm_out, check_point
net_input = net_input_saved
out = net(net_input)
if (out_avg is None):
out_avg = out.detach()
else:
out_avg = ((out_avg * exp_weight) + (out.detach() * (1 - exp_weight)))
total_loss = mse((out * mask_var), (... |
def check_k0(freqs, k0=None, rtol=0.01, atol=1e-07):
k0 = (k0 if (k0 is not None) else get_k0(freqs))
df = (freqs[1] - freqs[0])
f0 = (k0 * df)
assert (abs((f0 - freqs[0])) < ((rtol * df) + atol)) |
def ortho_weight(ndim):
W = numpy.random.randn(ndim, ndim)
(u, s, v) = numpy.linalg.svd(W)
return u.astype('float32') |
class FuseMatMulRequantizeDequantizeNewAPITransformer(GraphRewriterBase):
def __init__(self, model, device='cpu'):
super().__init__(model)
self.device = device
self.graph_analyzer = GraphAnalyzer()
self.graph_analyzer.graph = self.model
self.graph_info = self.graph_analyzer.p... |
class DiagonalGaussianDensity(Density):
def __init__(self, mean, stddev, num_fixed_samples=0):
super().__init__()
assert (mean.shape == stddev.shape)
self.register_buffer('mean', mean)
self.register_buffer('stddev', stddev)
if (num_fixed_samples > 0):
self.registe... |
def load_data(tr: Training, verbose=0):
list_train_ds = tf.data.Dataset.list_files([str((((tr.train_data_dir + '/') + ds) + '/*/images/*')) for ds in tr.train_datasets])
list_test_ds = tf.data.Dataset.list_files([str((((tr.test_data_dir + '/') + ds) + '/*/images/*')) for ds in tr.test_datasets])
train_data ... |
_model
def vit_base_r26_s32_224(pretrained=False, **kwargs):
backbone = _resnetv2((2, 2, 2, 2), **kwargs)
model_kwargs = dict(embed_dim=768, depth=12, num_heads=12, **kwargs)
model = _create_vision_transformer_hybrid('vit_base_r26_s32_224', backbone=backbone, pretrained=pretrained, **model_kwargs)
retur... |
def main():
args = init_args()
(x_val, y_val, z_val) = blh2xyz(args.b, args.l, args.h)
message = 'X: {:.5f}, Y: {:.5f}, Z: {:.5f}'
print(message.format(x_val, y_val, z_val))
return 0 |
def test_get_metrics_returns_dict():
(ground_truth, retrieved) = return_ground_incorrect_retrievals()
assert isinstance(get_all_metrics(ground_truth, retrieved), dict)
assert (len(get_all_metrics(ground_truth, retrieved).values()) == 3) |
_module()
class Rotate(GeomTransform):
def __init__(self, prob: float=1.0, level: Optional[int]=None, min_mag: float=0.0, max_mag: float=30.0, reversal_prob: float=0.5, img_border_value: Union[(int, float, tuple)]=128, mask_border_value: int=0, seg_ignore_label: int=255, interpolation: str='bilinear') -> None:
... |
class DDPMMeanLoss(nn.Module):
def __init__(self, *, reduce_mean: bool=True, likelihood_weighting: bool=False, eps_weighting: bool=False):
super().__init__()
self.reduce_mean = reduce_mean
self.likelihood_weighting = likelihood_weighting
self.eps_weighting = eps_weighting
def for... |
def to_str(segment):
assert (len(segment) == 3)
return '[{0:.3f}, {1:.3f}, {2}]'.format(segment[0], segment[1], segment[2]) |
def train(args, net, loss_function, data_iterator):
ctx = args.ctx[0]
local_cfg = cfg.STATIC_GRAPH
net.initialize(init=mx.init.Xavier(magnitude=3), ctx=ctx)
trainer = gluon.Trainer(net.collect_params(), local_cfg.MODEL.TRAIN.OPTIMIZER, {'learning_rate': local_cfg.MODEL.TRAIN.LR, 'wd': local_cfg.MODEL.TR... |
class TextualResEncoder(nn.Module):
def __init__(self, input_nc=3, ngf=32, z_nc=256, img_f=256, L=6, layers=5, norm='none', activation='ReLU', use_spect=True, use_coord=False, image_dim=256, text_dim=256, multi_peak=True, pool_attention='max'):
super(TextualResEncoder, self).__init__()
self.layers =... |
_model
def fbnetv3_d(pretrained=False, **kwargs):
model = _gen_fbnetv3('fbnetv3_d', pretrained=pretrained, **kwargs)
return model |
def data_provider(dataset_name, train_data_paths, valid_data_paths, batch_size, img_width, is_training=True):
if (dataset_name not in datasets_map):
raise ValueError(('Name of dataset unknown %s' % dataset_name))
train_data_list = train_data_paths.split(',')
valid_data_list = valid_data_paths.split(... |
class TestMSAColumnGlobalAttention(unittest.TestCase):
def test_shape(self):
batch_size = consts.batch_size
n_seq = consts.n_seq
n_res = consts.n_res
c_m = consts.c_m
c = 44
no_heads = 4
msagca = MSAColumnGlobalAttention(c_m, c, no_heads)
x = torch.ran... |
class DDIMScheduler(SchedulerMixin, ConfigMixin):
_compatibles = [e.name for e in KarrasDiffusionSchedulers]
order = 1
_to_config
def __init__(self, num_train_timesteps: int=1000, beta_start: float=0.0001, beta_end: float=0.02, beta_schedule: str='linear', trained_betas: Optional[Union[(np.ndarray, List... |
def test_setr_up_head(capsys):
with pytest.raises(AssertionError):
SETRUPHead(num_classes=19, kernel_size=2)
with pytest.raises(AssertionError):
SETRUPHead(in_channels=(4, 4), channels=2, num_classes=19)
head = SETRUPHead(in_channels=4, channels=2, norm_cfg=dict(type='SyncBN'), num_classes=1... |
_module()
class FCNHead(BaseDecodeHead):
def __init__(self, num_convs=2, kernel_size=3, concat_input=True, dilation=1, **kwargs):
assert ((num_convs >= 0) and (dilation > 0) and isinstance(dilation, int))
self.num_convs = num_convs
self.concat_input = concat_input
self.kernel_size = ... |
def get_dataset_params(is_gcloud=False, tfrecord_dir=constants.NVIDIA_CELEBA_HQ_DATASET_PATH_GCLOUD, **kwargs):
if is_gcloud:
return CelebAHQDatasetParams(gcs_bucket=constants.GCLOUD_BUCKET, tfrecord_dir=tfrecord_dir, **kwargs)
else:
return CelebAHQDatasetParams(**kwargs) |
def bg_white(seg, raw, blur_level=3, gaussian=81):
seg = cv2.blur(seg, (blur_level, blur_level))
empty = np.ones_like(seg)
seg_bg = ((empty - seg) * 255)
seg_bg = cv2.GaussianBlur(seg_bg, (gaussian, gaussian), 0)
background_mask = cv2.cvtColor((255 - cv2.cvtColor(seg, cv2.COLOR_BGR2GRAY)), cv2.COLOR... |
def test_disaggregated_scores_are_determinstic():
no_aggregation = calculate_rouge(PRED, TGT, bootstrap_aggregation=False, rouge_keys=['rouge2', 'rougeL'])
assert isinstance(no_aggregation, defaultdict)
no_aggregation_just_r2 = calculate_rouge(PRED, TGT, bootstrap_aggregation=False, rouge_keys=['rouge2'])
... |
def _find_my_group(grouped_ranks):
index = _find_my_group_index(grouped_ranks)
return grouped_ranks[index] |
_module()
class OBBRetinaHead(OBBAnchorHead):
def __init__(self, num_classes, in_channels, stacked_convs=4, conv_cfg=None, norm_cfg=None, anchor_generator=dict(type='AnchorGenerator', octave_base_scale=4, scales_per_octave=3, ratios=[0.5, 1.0, 2.0], strides=[8, 16, 32, 64, 128]), **kwargs):
self.stacked_con... |
class NfCfg():
depths: Tuple[(int, int, int, int)]
channels: Tuple[(int, int, int, int)]
alpha: float = 0.2
gamma_in_act: bool = False
stem_type: str = '3x3'
stem_chs: Optional[int] = None
group_size: Optional[int] = 8
attn_layer: Optional[str] = 'se'
attn_kwargs: dict = field(defaul... |
class PositionSortLauncher():
def __init__(self):
pass
def _no_opposite(self, handle):
return (not _has_opposite(self.env, handle))
def _by_cities(self):
self._city_n = ([(- 1)] * len(self.env.agents))
timer = 0
for (handle, agent) in enumerate(self.env.agents):
... |
def m_dreg_looser(model, x, K=1):
S = compute_microbatch_split(x, K)
x_split = zip(*[_x.split(S) for _x in x])
(lw, zss) = zip(*[_m_dreg_looser(model, _x, K) for _x in x_split])
lw = torch.cat(lw, 2)
zss = torch.cat(zss, 2)
with torch.no_grad():
grad_wt = (lw - torch.logsumexp(lw, 1, kee... |
def torch2numpy(input):
assert isinstance(input, torch.Tensor), type(input)
return input.detach().cpu().numpy() |
def process_feature(feature: example_pb2.Feature, typename: str, typename_mapping: Dict, key: str) -> np.ndarray:
field = feature.ListFields()[0]
(inferred_typename, value) = (field[0].name, field[1].value)
if (typename is not None):
tf_typename = typename_mapping[typename]
if (tf_typename !... |
def save_checkpoint(obj, directory, step_num, use_thread=False):
if use_thread:
warnings.warn('use_threads set to True, but done synchronously still')
os.makedirs(directory, exist_ok=True)
torch.save(obj, checkpoint_name(directory), pickle_module=pickle)
torch.save(obj, checkpoint_name(directory... |
def prepare_t5(tokenizer, data_dir, max_input_length, max_output_length, lower=True):
train_file = f'{data_dir}/train'
dev_file = f'{data_dir}/dev'
test_file = f'{data_dir}/test'
train_out = f'{data_dir}/train_{max_input_length}_{max_output_length}.t5'
dev_out = f'{data_dir}/dev_{max_input_length}_{... |
class simpleMLP(nn.Module):
def __init__(self, i_c=1, n_c=10):
super(simpleMLP, self).__init__()
self.flatten = Expression((lambda tensor: tensor.view(tensor.shape[0], (- 1))))
self.fc1 = nn.Linear((28 * 28), 256, bias=True)
self.fc2 = nn.Linear(256, 128, bias=True)
self.fc3 ... |
_features_generator('morgan_count')
def morgan_counts_features_generator(mol: Molecule, radius: int=MORGAN_RADIUS, num_bits: int=MORGAN_NUM_BITS) -> np.ndarray:
mol = (Chem.MolFromSmiles(mol) if (type(mol) == str) else mol)
features_vec = AllChem.GetHashedMorganFingerprint(mol, radius, nBits=num_bits)
featu... |
def initgen(mesh_size, freq=3, boundary='Periodic', dtype=None, device=None, batch_size=1):
xs = []
for k in range(batch_size):
xs.append(_initgen(mesh_size, freq=freq, boundary=boundary, dtype=dtype, device=device))
x = torch.stack(xs, dim=0)
if (batch_size == 1):
return x[0]
else:
... |
class RankingAndFitnessSelection(Selection[(List[S], List[S])]):
def __init__(self, max_population_size: int, reference_point: S, dominance_comparator: Comparator=DominanceComparator()):
super(RankingAndFitnessSelection, self).__init__()
self.max_population_size = max_population_size
self.do... |
def train_AugTune(args, io):
train_loader = DataLoader(ModelNet40(args, partition='train'), num_workers=8, batch_size=args.batch_size, shuffle=True, drop_last=True)
test_loader = DataLoader(ModelNet40(args, partition='test'), num_workers=8, batch_size=args.test_batch_size, shuffle=True, drop_last=False)
dev... |
def _prepare_output_docstrings(output_type, config_class):
docstrings = output_type.__doc__
lines = docstrings.split('\n')
i = 0
while ((i < len(lines)) and (re.search('^\\s*(Args|Parameters):\\s*$', lines[i]) is None)):
i += 1
if (i < len(lines)):
docstrings = '\n'.join(lines[(i + 1... |
class TestFoldBatchnorm(unittest.TestCase):
tf.compat.v1.disable_eager_execution()
x = tf.compat.v1.placeholder(tf.float32, [1, 224, 224, 3], name='input')
conv_weights = tf.compat.v1.get_variable('weight', [3, 3, 3, 32], initializer=tf.compat.v1.random_normal_initializer())
conv_bias = tf.compat.v1.get... |
def get_wsi_loader(data_dir, batch_size=1, shuffle=False, num_threads=2, train_eval_test='val', splitter_path='./', device_id=0, num_gpus=1, seed=1, bag_size=1024, label_csv_path='./', split_num=0):
eii = ExternalInputCallable(data_dir=data_dir, batch_size=batch_size, split_num=split_num, splitter_path=splitter_pat... |
class AlignTextModelTester():
def __init__(self, parent, batch_size=12, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_p... |
class TestCompletionDataset(unittest.TestCase):
def setUpClass(self):
self.tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
class TestArgs():
train_on_inputs = False
task = 'completion'
max_seq_length = 512
max_source_length = 256
data... |
(frozen=True)
class Task():
id: Optional[int]
name: str
description: str
version: str
problem: str
origin: str
config: dict
assets: List[Asset]
measures: Dict[(str, Measure)]
def measure(self, name: str) -> pd.DataFrame:
return self.measures[name].values
def scalar_me... |
def get_stat_in_paths(paths, dict_name, scalar_name):
if (len(paths) == 0):
return np.array([[]])
if (type(paths[0][dict_name]) == dict):
return [path[dict_name][scalar_name] for path in paths]
return [[info[scalar_name] for info in path[dict_name]] for path in paths] |
def read_csv(filename, loss_name='val/loss'):
import codecs
import csv
fit_out = {}
with codecs.open(filename, encoding='utf-8-sig') as f:
for row in csv.DictReader(f, skipinitialspace=True):
if row[loss_name]:
fit_out[row['epoch']] = {'val_loss': row[loss_name]}
... |
class Lexicon(lazydict):
def __init__(self, path=''):
self._path = path
def path(self):
return self._path
def load(self):
dict.update(self, (x.split(' ')[:2] for x in _read(self._path) if (len(x.split(' ')) > 1))) |
class CamembertConfig(RobertaConfig):
pretrained_config_archive_map = CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP
model_type = 'camembert' |
class MobileBertForQuestionAnswering(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def evaluate(model):
model.compile(run_eagerly=False)
postprocess = LabelShift(label_shift=1)
from neural_compressor import METRICS
metrics = METRICS('tensorflow')
metric = metrics['topk']()
latency_list = []
def eval_func(dataloader, metric):
warmup = 5
iteration = None
... |
def factors(n):
lst = []
i = 1
while (i <= n):
if ((n % i) == 0):
lst.append(i)
i += 1
return lst |
(t='double', spline='Spline', returns='double')
def scale_factor(t=(- 1)):
if (not enable_Hubble):
return 1
if (t == (- 1)):
t = universals.t
spline = temporal_splines.t_a
if (spline is None):
abort('The function a(t) has not been tabulated. Have you called init_time?')
retur... |
def processed(f):
(f)
def wrapper(*args, **kwargs):
func = Process(target=f, args=args, kwargs=kwargs)
func.daemon = False
func.start()
return func
return wrapper |
def dataset_renderer_worker(log_ids: List[str], start_idx: int, end_idx: int, worker_id: int, kwargs: Mapping[(str, Any)]) -> None:
logging.info(f'Worker {worker_id} started...')
local_dataset_dir = kwargs['local_dataset_dir']
config = kwargs['config']
dataloader = kwargs['dataloader']
use_gpu = (is... |
class CiderScorer(object):
def copy(self):
new = CiderScorer(n=self.n)
new.ctest = copy.copy(self.ctest)
new.crefs = copy.copy(self.crefs)
return new
def copy_empty(self):
new = CiderScorer(df_mode='corpus', n=self.n, sigma=self.sigma)
new.df_mode = self.df_mode
... |
class Config():
library_path = None
library_file = None
compatibility_check = False
loaded = False
def set_library_path(path):
if Config.loaded:
raise Exception('library path must be set before before using any other functionalities in libclang.')
Config.library_path = pa... |
class AdaINorm2d(_AdaINorm):
def _check_input_dim(self, input):
if (input.dim() != 4):
raise ValueError('expected 4D input (got {}D input)'.format(input.dim())) |
def remove_tmp_file(func):
(func)
def wrapper(*args, **kwargs):
onnx_file = 'tmp.onnx'
kwargs['onnx_file'] = onnx_file
try:
result = func(*args, **kwargs)
finally:
if os.path.exists(onnx_file):
os.remove(onnx_file)
return result
... |
def adjust_axes(r, t, fig, axes):
bb = t.get_window_extent(renderer=r)
text_width_inches = (bb.width / fig.dpi)
current_fig_width = fig.get_figwidth()
new_fig_width = (current_fig_width + text_width_inches)
propotion = (new_fig_width / current_fig_width)
x_lim = axes.get_xlim()
axes.set_xlim... |
(scope='module')
def lapicque_hidden_reset_none_instance():
return snn.Lapicque(beta=0.5, init_hidden=True, reset_mechanism='none') |
def gen_voxel(cropped, com_2d, cube, voxel_len):
(H, W) = cropped.shape
x = np.arange(H)
y = np.arange(W)
(x, y) = np.meshgrid(x, y, indexing='ij')
z = cropped.copy()
mask = np.bitwise_and((cropped >= (com_2d[2] - (cube[2] / 2.0))), (cropped < (com_2d[2] + (cube[2] / 2.0))))
mask = mask.resh... |
def eval_test(model, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for (data, target) in test_loader:
(data, target) = (data.cuda(), target.cuda())
output = model(data)
test_loss += F.cross_entropy(output, target, size_average=Fals... |
def get_flat_arcs(index, sen):
sid = sen.id
arcs = []
for (j, token) in enumerate(sen):
form = token.form
lemma = token.lemma
upos = token.upos
xpos = token.xpos
deprel = token.deprel
if token.scope:
for (head, lbl) in token.scope:
... |
class OneInstanceLauncher(Launcher):
def launch(self, args, memory_prefix_list):
processes = []
cmd = []
cmd_for_print = []
processes = []
tmp_log_path = ''
cores = 1
current_path = os.path.abspath(os.getcwd())
batch_size_list = []
if (args.bat... |
_module()
class ADE20KDataset(CustomDataset):
CLASSES = ('wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road', 'bed ', 'windowpane', 'grass', 'cabinet', 'sidewalk', 'person', 'earth', 'door', 'table', 'mountain', 'plant', 'curtain', 'chair', 'car', 'water', 'painting', 'sofa', 'shelf', 'house', 'sea', 'mir... |
def get_mean_std(exp_name):
root_path = '/data/sls/scratch/yuangong/avbyol/egs/vggsound/exp/'
three_res = []
for repeat in ['-r1', '-r2', '-r3']:
cur_res = (np.loadtxt((((root_path + exp_name) + repeat) + '/result.csv'), delimiter=',') * 100)
three_res.append(cur_res)
three_res = np.stac... |
_config
def pnn_rigidity():
cfg = {'learner': {'model': 'LifelongSidetuneNetwork', 'model_kwargs': {'use_baked_encoding': False, 'base_class': 'TaskonomyEncoderWithCache', 'side_class': 'FCN5ProgressiveH', 'pnn': True, 'dense': False}}} |
class VisionTextDualEncoderProcessor(ProcessorMixin):
attributes = ['image_processor', 'tokenizer']
image_processor_class = 'AutoImageProcessor'
tokenizer_class = 'AutoTokenizer'
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
if ('feature_extractor' in kwargs):
w... |
def generate_regnet_parameters(w_a, w_0, w_m, d, q=8):
assert ((w_a >= 0) and (w_0 > 0) and (w_m > 1) and ((w_0 % q) == 0))
ws_cont = ((np.arange(d) * w_a) + w_0)
ks = np.round((np.log((ws_cont / w_0)) / np.log(w_m)))
ws_all = (w_0 * np.power(w_m, ks))
ws_all = (np.round(np.divide(ws_all, q)).astype... |
class MotionEncoderBiGRUCo(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(MotionEncoderBiGRUCo, self).__init__()
self.input_emb = nn.Linear(input_size, hidden_size)
self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True, bidirectional=True)
self.out... |
def prepare_minibatch(egs_file, minibatch_size):
egs = load_egs(egs_file)
random.shuffle(egs)
merged_egs = kaldi.chain.MergeChainEgs(egs, str(minibatch_size))
return merged_egs |
class TensorboardManager():
def __init__(self, path):
self.writer = tensorboardX.SummaryWriter(path)
def update(self, split, step, vals):
for (k, v) in vals.items():
self.writer.add_scalar(('%s_%s' % (split, k)), v, step)
def close(self):
self.writer.flush()
self.... |
class TrendBlock(Block):
def __init__(self, units, thetas_dim, past_seq_len=10, future_seq_len=5, nb_harmonics=None):
super(TrendBlock, self).__init__(units, thetas_dim, past_seq_len, future_seq_len, share_thetas=True)
def forward(self, x):
x = super(TrendBlock, self).forward(x)
backcast... |
class TestStochasticSwap(QiskitTestCase):
def test_multiple_registers_with_layout_adjust(self):
coupling = CouplingMap([[0, 1], [1, 2]])
qr_q = QuantumRegister(2, 'q')
qr_a = QuantumRegister(1, 'a')
cr_c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(qr_q, qr_a, cr_c)
... |
class ImageMirror(ImagePreprocessing):
def __init__(self, bigdl_type='float'):
super(ImageMirror, self).__init__(bigdl_type) |
def get_available_gpus(session_config=None):
if (session_config is None):
session_config = get_session()._config
from tensorflow.python.client import device_lib
local_device_protos = device_lib.list_local_devices(session_config)
return [x.name for x in local_device_protos if (x.device_type == 'G... |
class LayoutLMv3Processor(ProcessorMixin):
attributes = ['image_processor', 'tokenizer']
image_processor_class = 'LayoutLMv3ImageProcessor'
tokenizer_class = ('LayoutLMv3Tokenizer', 'LayoutLMv3TokenizerFast')
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
if ('feature_extrac... |
class ROIAlign3d(nn.Module):
def __init__(self, output_size, spatial_scale, sampling_ratio):
super(ROIAlign3d, self).__init__()
self.output_size = output_size
self.spatial_scale = spatial_scale
self.sampling_ratio = sampling_ratio
def forward(self, input, rois):
return ro... |
class StableDiffusionOnnxPipeline(metaclass=DummyObject):
_backends = ['torch', 'transformers', 'onnx']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch', 'transformers', 'onnx'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['torch', 'transformers', 'onn... |
def preprocess_org_min_date(path=DATA_PATH, file=DATA_FILE, path_proc=DATA_PATH_PROCESSED, min_item_support=MIN_ITEM_SUPPORT, min_session_length=MIN_SESSION_LENGTH, min_date=MIN_DATE):
data = load_data((path + file))
data = filter_data(data, min_item_support, min_session_length)
data = filter_min_date(data,... |
class DropdownSelectionWidget(Widget):
def __init__(self, options, value, description, parameter_dict, **kwargs):
super().__init__(**kwargs)
self.drop_down = widgets.Dropdown(options=options, value=value, description=description, disabled=False)
self.parameter_dict = parameter_dict
s... |
def apk(actual, predicted, k=10):
if (len(predicted) > k):
predicted = predicted[:k]
score = 0.0
num_hits = 0.0
for (i, p) in enumerate(predicted):
if ((p in actual) and (p not in predicted[:i])):
num_hits += 1.0
score += (num_hits / (i + 1.0))
if (not actual)... |
.slow
def test_factorized_antisymmetry_can_be_evaluated():
(key, init_pos, slog_psis) = _make_factorized_antisymmetries()
[_jit_eval_model_and_verify_output_shape(key, init_pos, slog_psi) for slog_psi in slog_psis] |
class HeteroDotProductPredictor(nn.Module):
def forward(self, graph, h, etype):
with graph.local_scope():
graph.ndata['h'] = h
graph.apply_edges(fn.u_dot_v('h', 'h', 'score'), etype=etype)
return graph.edges[etype].data['score'] |
def get_cosine_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float=0.5, last_epoch: int=(- 1), min_lr_ratio: float=0.0):
lr_lambda = partial(_get_cosine_schedule_with_warmup_lr_lambda, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, ... |
class XNet_sb(nn.Module):
def __init__(self, in_channels, num_classes):
super(XNet_sb, self).__init__()
(l1c, l2c, l3c, l4c, l5c) = (64, 128, 256, 512, 1024)
self.b1_1_1 = nn.Sequential(conv3x3(in_channels, l1c), conv3x3(l1c, l1c), BasicBlock(l1c, l1c))
self.b1_1_2_down = down_conv(l... |
def dump_fold_into_csv_CUB(lsamples, outpath, tag):
msg = "'tag' must be an integer. Found {}.".format(tag)
assert isinstance(tag, int), msg
msg = "'tag' = {} is unknown. Please see constants.samples_tags = {}.".format(tag, constants.samples_tags)
assert (tag in constants.samples_tags), msg
assert (... |
def cifar_model_large(conv_layer, linear_layer, init_type, **kwargs):
assert (init_type == 'kaiming_normal'), 'only supporting kaiming_normal init'
model = nn.Sequential(conv_layer(3, 32, 3, stride=1, padding=1), nn.ReLU(), conv_layer(32, 32, 4, stride=2, padding=1), nn.ReLU(), conv_layer(32, 64, 3, stride=1, p... |
def init(model_s, model_t, init_modules, criterion, train_loader, logger, opt):
model_t.eval()
model_s.eval()
init_modules.train()
if torch.cuda.is_available():
model_s.cuda()
model_t.cuda()
init_modules.cuda()
cudnn.benchmark = True
if ((opt.model_s in ['resnet8', 'r... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=(1, 1), residual=True, BatchNorm=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = BatchNorm(planes)
... |
class Net(torch.nn.Module):
def __init__(self, train_dataset):
super(Net, self).__init__()
self.conv1 = GATConv(train_dataset.num_features, 256, heads=4)
self.lin1 = torch.nn.Linear(train_dataset.num_features, (4 * 256))
self.conv2 = GATConv((4 * 256), 256, heads=4)
self.lin2... |
def test(args, model, device, test_loader, logger):
model.eval()
with torch.no_grad():
for (data, target) in test_loader:
start = time()
(data, target) = (data.to(device), target.to(device))
predictions = model(data)
loss = F.cross_entropy(predictions, tar... |
class Adjective_Rate(object):
def __init__(self, sentence_objs):
self.sentence_objs = sentence_objs
def handle(self):
(tot_num_adjs, tot_num_words) = (0, 0)
for so in self.sentence_objs:
tot_num_adjs += so.pos_tag_counter.get_pos_tag_count(ADJECTIVE)
tot_num_words... |
def clear_dir(directory):
if (not os.path.isdir(directory)):
raise Exception(('%s is not a directory' % directory))
if (type(directory) != str):
raise Exception(('string type required for directory: %s' % directory))
if (directory in ['..', '.', '', '/', './', '../', '*']):
raise Exc... |
def get_config(num_targets):
if ((num_targets == 0) or (not isinstance(num_targets, int))):
raise ValueError(f'num_targets is {num_targets}, but must be a positive integer')
screen = sprite.Sprite(x=0.5, y=0.5, shape='square', scale=2.0, c0=0.6, c1=0.7, c2=0.7)
target_factor_distrib = distribs.Produ... |
def plot_alignment_to_numpy(alignment, info=None):
global MATPLOTLIB_FLAG
if (not MATPLOTLIB_FLAG):
import matplotlib
matplotlib.use('Agg')
MATPLOTLIB_FLAG = True
mpl_logger = logging.getLogger('matplotlib')
mpl_logger.setLevel(logging.WARNING)
import matplotlib.pylab... |
def parse_dict_args(**kwargs):
def to_cmdline_kwarg(key, value):
if (len(key) == 1):
key = '-{}'.format(key)
else:
key = '--{}'.format(re.sub('_', '-', key))
value = str(value)
return (key, value)
kwargs_pairs = (to_cmdline_kwarg(key, value) for (key, valu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.