code stringlengths 101 5.91M |
|---|
def construct_length_mask(seq_lengths):
max_sequence_length = max(seq_lengths)
mask = torch.zeros([len(seq_lengths), max_sequence_length]).bool()
for (line, length) in zip(mask, seq_lengths):
line[:length] = True
return mask |
def dobldobl_estimated_distance():
from phcpy.phcpy2c3 import py2c_padcon_dobldobl_estimated_distance
return py2c_padcon_dobldobl_estimated_distance() |
def load_weights(output_folder, weight_load_name, num_layers):
weights = []
biases = []
for i in xrange(0, (num_layers + 1)):
weight_i = np.loadtxt(((((output_folder + weight_load_name) + '/w_') + str(i)) + '.txt'), delimiter=',')
w_i = tf.Variable(weight_i, dtype=tf.float32)
weights... |
def main():
m = build_low_latency_conv(41, 40)
m.summary()
m = build_tiny_conv(32, 40)
m.summary()
m = build_one()
m.summary() |
def get_bucketer(method, encoding_method=None, case_id_col=None, cat_cols=None, num_cols=None, n_clusters=None, random_state=None, n_neighbors=None):
if (method == 'cluster'):
bucket_encoder = EncoderFactory.get_encoder(method=encoding_method, case_id_col=case_id_col, dynamic_cat_cols=cat_cols, dynamic_num_... |
def render_pose(cfg, i4d, dataset, epoch, specific_obj, pose):
basedir = cfg.basedir
expname = cfg.expname
dataloader = dataset.get_loader(num_workers=0)
savedir = os.path.join(basedir, expname, 'renderings', f'{specific_obj}_epoch_{epoch}_renderfactor_{cfg.render_factor}_batch_{cfg.fixed_batch}')
o... |
class DebugVisualizer():
def __init__(self):
plt.figure(1)
self.debug_lines = [plt.plot([], color='tab:orange')[0] for _ in range(4)]
self.debug_texts = [plt.text(0, 0, None, ha='center', va='center') for _ in range(4)]
def draw_debug_data(self, debug_data):
for i in range(4):
... |
class RRDBNet(nn.Module):
def __init__(self, in_nc, out_nc, nf, nb, gc=32, upscale=4):
super(RRDBNet, self).__init__()
RRDB_block_f = functools.partial(RRDB, nf=nf, gc=gc)
self.conv_first = nn.Conv2d(in_nc, nf, 3, 1, 1, bias=True)
self.RRDB_trunk = make_layer(RRDB_block_f, nb)
... |
class BaseContrastSpladeFinetuner():
def get_quadratic_increase_flop_factor(self, flop_factor):
if (self.state.epoch >= self.args.flop_increase_epoch_factor):
return flop_factor
else:
return (flop_factor * ((self.state.epoch / self.args.flop_increase_epoch_factor) ** 2))
... |
class BertConfig(PretrainedConfig):
model_type = 'bert'
def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initia... |
class iCIFAR100(iCIFAR10):
base_dataset = datasets.cifar.CIFAR100
base_dataset_hierarchy = cifar_info.CIFAR100
common_transforms = [transforms.ToTensor(), transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761))]
class_order = [87, 0, 52, 58, 44, 91, 68, 97, 51, 15, 94, 92, 10, 72, 49, 7... |
class Normalize(object):
def __init__(self, mean, std):
self.mean = mean
self.std = std
def __call__(self, tensor, mask):
return (F.normalize(tensor, self.mean, self.std), mask) |
def evaluate(args, model):
dev_dataset = SequenceDataset(TextTokenIdsCache(args.preprocess_dir, f'{args.mode}-query'), args.max_seq_length)
collate_fn = get_collate_function(args.max_seq_length)
batch_size = args.pergpu_eval_batch_size
if (args.n_gpu > 1):
batch_size *= args.n_gpu
dev_datalo... |
def load_gptq_model():
model_name_or_path = 'TheBloke/falcon-7b-instruct-GPTQ'
model_basename = 'gptq_model-4bit-64g'
use_triton = False
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, use_fast=True)
model = AutoGPTQForCausalLM.from_quantized(model_name_or_path, model_basename=model_ba... |
class Hswish(nn.Module):
def __init__(self, inplace=True):
super(Hswish, self).__init__()
self.inplace = inplace
def forward(self, x):
return ((x * F.relu6((x + 3.0), inplace=self.inplace)) / 6.0) |
def rotate_points(points, bbox):
tl_corner = (bbox[0], bbox[2])
distances = []
for point in points:
distances.append(get_distance(point, tl_corner))
min_index = np.argsort(distances)[0]
return (points[min_index:] + points[:min_index]) |
_charset('fr')
class FrCharSet(BaseCharset):
_CHARS = u'abcdefghijklmnopqrstuvwxyz'
_FEATURES = ['capitalization'] |
def test_audio_datamodule_prepare_download_archive(fs, mocker):
mocked_download = mocker.patch(f'{TESTED_MODULE}.data_utils.download_file_r2')
mocked_extract = mocker.patch(f'{TESTED_MODULE}.extract_archive')
data = AudioDataModule()
data.prepare_data()
assert (mocked_download.call_args_list == [moc... |
class MemorySummary(NamedTuple):
sequential: List[MemoryState]
cumulative: List[MemoryState]
current: List[MemoryState]
total: Memory |
class Estimator(object):
def from_keras(*, model_creator: Optional[Callable]=None, config: Optional[Dict]=None, verbose: bool=False, workers_per_node: int=1, compile_args_creator: Optional[Callable]=None, backend: str='ray', cpu_binding: bool=False, log_to_driver: bool=True, model_dir: Optional[str]=None, **kwargs)... |
def get_parser():
parser = argparse.ArgumentParser(description='RIASS')
parser.add_argument('--resume', dest='resume', action='store_true', help='whether to resume training an existing model (the one with name model_name will be used)')
parser.set_defaults(resume=False)
parser.add_argument('-epoch_resum... |
def __save_loss(losses, file_path):
pd.DataFrame(data=losses, columns=['epoch', 'batch', 'train_loss', 'val_loss']).to_csv(file_path, index=False) |
class GrapplerOptimizer(GraphRewriterBase):
def __init__(self, model, input_output_names, opt_cfg):
super().__init__(model)
self.input_output_names = input_output_names
self.opt_cfg = opt_cfg
self.generic_optimizer = ('pruning', 'shape', 'dependency', 'debug_stripper', 'loop')
... |
class BasicBlock2D(nn.Module):
def __init__(self, in_channels, out_channels, **kwargs):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, **kwargs)
self.bn = nn.BatchNor... |
class Video():
def __init__(self, video_id):
self.posetrack_video_id = video_id
self.frames = []
def to_new(self):
result = {'images': [], 'annotations': []}
for image in self.frames:
image_json = image.to_new()
image_json['vid_id'] = self.posetrack_video_... |
def learn(*, env, num_epoch, seed=None, eval_env=None, replay_strategy='future', policy_save_interval=5, clip_return=True, demo_file=None, override_params=None, load_model=False, load_buffer=False, load_path=None, save_path=None, play_no_training=False, offline_train=False, mode=None, su_method='', **kwargs):
overr... |
def ycbcr2rgb(img):
img_type = img.dtype
img = (_convert_input_type_range(img) * 255)
out_img = ((np.matmul(img, [[0., 0., 0.], [0, (- 0.), 0.], [0., (- 0.), 0]]) * 255.0) + [(- 222.921), 135.576, (- 276.836)])
out_img = _convert_output_type_range(out_img, img_type)
return out_img |
def training_batch_item_task(batch_index, model, sess, train_data, is_training):
for index in batch_index:
(_, support_user, target_item) = fbne_data.batch_gen_item_task(train_data, index, setting.batch_size)
feed_dict = {model.support_user: support_user, model.target_item: target_item, model.traini... |
_torch
_vision
class BlipImageProcessingTest(ImageProcessingSavingTestMixin, unittest.TestCase):
image_processing_class = (BlipImageProcessor if is_vision_available() else None)
def setUp(self):
self.image_processor_tester = BlipImageProcessingTester(self)
def image_processor_dict(self):
ret... |
class HmEncoder(object):
def __init__(self, cols=None):
self.enc = HelmertEncoder(cols=cols, verbose=1, mapping=None, drop_invariant=False, return_df=True, handle_unknown='value', handle_missing='value')
def fit(self, X):
with warnings.catch_warnings():
warnings.simplefilter('ignore'... |
class BehaviorCloning(OffPolicyAlgorithm):
def __init__(self, *args, grad_norm_clip: Optional[float]=None, bc_data: str='all', bc_all_steps: int=0, **kwargs) -> None:
super().__init__(*args, **kwargs)
assert ('encoder' in self.network.CONTAINERS)
assert ('actor' in self.network.CONTAINERS)
... |
def test_can_instantiate_from_loss_config(loss_cfg, parser):
cfg_string = read_cfg(loss_cfg)
parser.add_argument('cfg', type=Union[(Callable, torch.nn.Module)])
args = parser.parse_string(cfg_string)
assert ('class_path' in args.cfg), 'No class_path key in config root level'
class_path = args.cfg['c... |
def test_classification_metrics_integrated():
ground_truth = {'1': ['2', '3', '4'], '2': ['1', '3'], '3': ['1', '2'], '4': ['1']}
retrieved = {'1': ['2', '3'], '2': ['1'], '3': ['1'], '4': []}
expected_return = {'precision': np.array([0.5, 1.0]), 'recall': np.array([1.0, 0.5]), 'f1_score': np.array([0., 0.]... |
def _generate_teams() -> pd.DataFrame:
start_season = 1876
end_season = most_recent_season()
lahman_columns = ['yearID', 'lgID', 'teamID', 'franchID', 'divID', 'name', 'teamIDBR', 'teamIDlahman45', 'teamIDretro']
lahman_teams = lahman.teams_core().query('yearID >= _season')[lahman_columns]
fg_team_d... |
def polar_gen_isic2018():
data_dir = '/raid/wjc/data/skin_lesion/isic2018_jpg_smooth/'
os.makedirs((data_dir + '/PolarImage'), exist_ok=True)
os.makedirs((data_dir + '/PolarLabel'), exist_ok=True)
path_list = os.listdir((data_dir + '/Label/'))
path_list.sort()
num = 0
for path in tqdm(path_l... |
def nfsp_leduc_dqn_params(env: MultiAgentEnv) -> Dict[(str, Any)]:
return merge_dicts(GRL_DEFAULT_OPENSPIEL_POKER_DQN_PARAMS, {'exploration_config': {'type': ValidActionsEpsilonGreedy, 'initial_epsilon': 0.06, 'final_epsilon': 0.001, 'epsilon_timesteps': int(.0)}, 'num_gpus': float(os.getenv('WORKER_GPU_NUM', 0.0))... |
class PreprocessEnv(habitat.RLEnv):
def __init__(self, env, preprocessing_fn=None):
self.env = env
self.transform = None
self.observation_space = self.env.observation_space
if (preprocessing_fn is not None):
(self.transform, self.observation_space) = preprocessing_fn(self... |
def embedding(hparams, eval_loader, pred_loader, exp_dir, data_tag):
model_info = dict(hparams.model)
model = getattr(model_arch, model_info['type'])(**model_info['args'])
model.to(device)
checkpt = torch.load(((exp_dir + '/') + hparams.best_model), map_location=device)
model.load_state_dict(checkpt... |
class VCTreeLSTMContext(nn.Module):
def __init__(self, cfg, obj_classes, rel_classes, statistics, in_channels):
super(VCTreeLSTMContext, self).__init__()
self.cfg = cfg
self.obj_classes = obj_classes
self.rel_classes = rel_classes
self.num_obj_classes = len(obj_classes)
... |
def dump_class_labels(s_ids: dict, old_meta, new_meta):
infile = open(old_meta.class_labels, 'r')
outfile = open(new_meta.class_labels, 'w')
for line in infile.readlines():
(image_id, class_label_string) = line.strip('\n').split(',')
if (image_id in s_ids.keys()):
outfile.write(l... |
class InceptionI3d(snt.AbstractModule):
VALID_ENDPOINTS = ('Conv3d_1a_7x7', 'MaxPool3d_2a_3x3', 'Conv3d_2b_1x1', 'Conv3d_2c_3x3', 'MaxPool3d_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool3d_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool3d_5a_2x2', 'Mixed_5b', 'Mixed_5c', 'Logits', 'Predict... |
def train_beta(model):
print('Starting initial training (with cropped images)')
num_epochs = 100
batch_size = 2
nframes = 14
nframes_val = 32
size = (480, 864)
def image_read(path):
pic = Image.open(path)
transform = tv.transforms.Compose([tv.transforms.Resize(size, interpola... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--datasets', nargs='+', default=penn.EVALUATION_DATASETS, help='The datasets to evaluate on')
parser.add_argument('--checkpoint', type=Path, help='The checkpoint file to evaluate')
parser.add_argument('--gpu', type=int, help='The ... |
def _create_or_get_iterations_per_loop():
graph = ops.get_default_graph()
collection_name = '{}_{}'.format(_TPU_ESTIMATOR, _ITERATIONS_PER_LOOP_VAR)
iter_vars = graph.get_collection(collection_name)
if (len(iter_vars) == 1):
return iter_vars[0]
elif (len(iter_vars) > 1):
raise Runtim... |
def import_tinyImagenet_task():
try:
import sys
sys.path.insert(0, '/export/home/sicarbonnell/Recherche/_datasets')
from import_tinyImagenet import import_tinyImagenet
except:
raise ImportError('Our code does not provide the utilities to load the tinyImagenet dataset.')
(x_tr... |
def log_cfg(cfg: Dict, prefix: str='cfg') -> None:
logger = logging.getLogger(__name__)
for (k, v) in cfg.items():
if isinstance(v, dict):
p = '.'.join([prefix, k])
log_cfg(v, prefix=p)
else:
p = '.'.join([prefix, k])
logger.info('%34s : %s', p, v) |
def create_metadata_with_new_checkpoint_for_current_best_response(trainer: Trainer, player: int, save_dir: str, timesteps_training_br: int, episodes_training_br: int, active_policy_num: int=None, average_br_reward: float=None):
return {'checkpoint_path': save_policy_checkpoint(trainer=trainer, player=player, save_d... |
class StatusEnum(enum.Enum):
READY = 0
RUNNING = 1
COMPLETE = 2
ERROR = 3
SUSPENDED = 4 |
class _FunctionState(object):
_NORMAL_TRIGGER = 250
_TEST_TRIGGER = 400
def __init__(self):
self.in_a_function = False
self.lines_in_function = 0
self.current_function = ''
def Begin(self, function_name):
self.in_a_function = True
self.lines_in_function = 0
... |
def get_parser():
parser = argparse.ArgumentParser('SampleNet: Differentiable Point Cloud Sampling')
parser.add_argument('--skip-projection', action='store_true', help='Do not project points in training')
parser.add_argument('-in', '--num-in-points', type=int, default=1024, help='Number of input Points [def... |
def make_dataset(classlist, labellist=None):
images = []
labels = []
classes = utils.readtextfile(ifile)
classes = [x.rstrip('\n') for x in classes]
classes.sort()
for i in len(classes):
for fname in os.listdir(classes[i]):
if is_image_file(fname):
label = {}
... |
def parallel_download_s3_objects(s3_files, destination_filepaths, bucket_name, process_pool_size=None):
if (process_pool_size is None):
process_pool_size = cpu_count()
s3_and_destination = zip(s3_files, destination_filepaths)
with Pool(process_pool_size, init_s3_client) as proc:
results = pr... |
def run(settings):
settings.device = 'cuda'
settings.description = 'TransT with default settings.'
settings.batch_size = 32
settings.num_workers = 4
settings.multi_gpu = True
settings.print_interval = 1
settings.normalize_mean = [0.485, 0.456, 0.406]
settings.normalize_std = [0.229, 0.22... |
class M2M100Config(PretrainedConfig):
model_type = 'm2m_100'
keys_to_ignore_at_inference = ['past_key_values']
attribute_map = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}
def __init__(self, vocab_size=128112, max_position_embeddings=1024, encoder_layers=12, encoder_ffn_d... |
def rbm(name, n_components=None, learning_rate=None, batch_size=None, n_iter=None, verbose=False, random_state=None):
def _name(msg):
return ('%s.%s_%s' % (name, 'rbm', msg))
rval = scope.sklearn_BernoulliRBM(n_components=(scope.int(hp.qloguniform((name + '.n_components'), low=np.log(0.51), high=np.log(... |
class TFBackend():
def __init__(self, tf):
self._tf = tf
for k in dir(tf):
setattr(self, k, getattr(tf, k))
self.min = tf.minimum
self.max = tf.maximum
def with_same_type(self, x, other):
if (not self._tf.is_tensor(x)):
x = (self._tf.ones_like(othe... |
class DistillationLoss(torch.nn.Module):
def __init__(self, base_criterion: torch.nn.Module, teacher_model: torch.nn.Module, distillation_type: str, alpha: float, tau: float):
super().__init__()
self.base_criterion = base_criterion
self.teacher_model = teacher_model
assert (distillat... |
class Swinv2Config(PretrainedConfig):
model_type = 'swinv2'
attribute_map = {'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}
def __init__(self, image_size=224, patch_size=4, num_channels=3, embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, mlp_ratio=4.0, qkv_... |
def load_data(location='/tmp/.zoo/dataset/mnist'):
(train_images, train_labels) = read_data_sets(location, 'train')
(test_images, test_labels) = read_data_sets(location, 'test')
return ((train_images, train_labels), (test_images, test_labels)) |
class MaskedLMConfig(FairseqDataclass):
data: str = field(default=MISSING, metadata={'help': 'colon separated path to data directories list, will be iterated upon during epochs in round-robin manner'})
sample_break_mode: SAMPLE_BREAK_MODE_CHOICES = field(default='none', metadata={'he... |
def sum_space(sizes):
if isinstance(sizes, tuple):
if (len(sizes) == 0):
return 0
elif (type(sizes[0]) == int):
return np.prod(list(sizes))
else:
return sum_space(list(sizes))
elif isinstance(sizes, list):
return np.sum([sum_space(x) for x in s... |
def sample_list_to_type(dtype, t):
if isinstance(t, Dict):
for (k, v) in t.items():
if isinstance(v, Tensor):
if v.is_floating_point():
t[k] = v.to(dtype)
return t
elif isinstance(t, List):
for (i, elem) in enumerate(t):
if isin... |
class HMNetTrainer(DistributedTrainer):
def __init__(self, opt):
super().__init__(opt)
self.task = Task.setup_task(self.opt['TASK'], self.opt, self.saveFolder)
def is_gradient_accumulation_boundary(self):
return (((self.updates + 1) % self.grad_acc_steps) == 0)
def get_batch_generato... |
def video_to_imgs(video_name='demo_output.mp4', image_dir='./images/'):
video_capture = VideoCapture(video_name)
number = 0
while True:
(flag, frame) = video_capture.read()
if (flag is False):
break
(w, h) = (frame.shape[0], frame.shape[1])
if (((w % 4) != 0) or (... |
class AsyncRlEval(AsyncRlBase):
_eval = True
def initialize_logging(self):
self._traj_infos = list()
self._last_eval_time = 0.0
super().initialize_logging()
self.pbar = ProgBarCounter(self.log_interval_itrs)
def log_diagnostics(self, itr, sampler_itr, throttle_time):
... |
def test_mask2ndarray():
raw_masks = np.ones((3, 28, 28))
bitmap_mask = BitmapMasks(raw_masks, 28, 28)
output_mask = mask2ndarray(bitmap_mask)
assert np.allclose(raw_masks, output_mask)
raw_masks = dummy_raw_polygon_masks((3, 28, 28))
polygon_masks = PolygonMasks(raw_masks, 28, 28)
output_ma... |
class DownsampleLayer(nn.Module):
def __init__(self, channels, norm_layer='LN'):
super().__init__()
self.conv = nn.Conv2d(channels, (2 * channels), kernel_size=3, stride=2, padding=1, bias=False)
self.norm = build_norm_layer((2 * channels), norm_layer, 'channels_first', 'channels_last')
... |
def test_dissipativeforce_method_inputAsQuantity():
from galpy.potential import ChandrasekharDynamicalFrictionForce
from galpy.util import conversion
(ro, vo) = ((8.0 * units.kpc), 220.0)
pot = ChandrasekharDynamicalFrictionForce(GMs=0.1, rhm=(1.2 / 8.0), ro=ro, vo=vo)
potu = ChandrasekharDynamicalF... |
class LinspaceRange(Range[float]):
def __init__(self, start: float, end: float, n: int, name: Optional[str]=None, dtype=None) -> None:
self.n = n
self.start = start
self.end = end
self.dtype = dtype
super().__init__(name)
def values(self) -> np.ndarray:
return np.... |
def get_embedding(args):
print('{}, Building augmented embedding'.format(datetime.datetime.now().strftime('%02y/%02m/%02d %H:%M:%S')))
aux = []
for ebd in args.auxiliary:
if (ebd == 'pos'):
aux.append(POS(args))
else:
raise ValueError('Invalid argument for auxiliary e... |
class NopModule(MsfModule):
def __init__(self, rpc, nop):
super(NopModule, self).__init__(rpc, 'nop', nop) |
def make_atom14_masks(protein: Dict[(str, torch.Tensor)]) -> Dict[(str, torch.Tensor)]:
restype_atom14_to_atom37_list = []
restype_atom37_to_atom14_list = []
restype_atom14_mask_list = []
for rt in rc.restypes:
atom_names = rc.restype_name_to_atom14_names[rc.restype_1to3[rt]]
restype_ato... |
def AusElectricity_train(sample):
if sample:
return {'class_balance': (lambda r: True), 'weight_decay': (lambda r: 0.0), 'lr': (lambda r: (10 ** r.uniform((- 5), (- 3)))), 'batch_size': (lambda r: int((2 ** r.uniform(3, 5))))}
else:
return {'class_balance': (lambda r: True), 'weight_decay': (lam... |
class BertChecker(BertPreTrainedModel):
def __init__(self, config, logic_lambda=0.0, prior='nli', m=8, temperature=1):
super().__init__(config)
self.num_labels = config.num_labels
self.hidden_size = config.hidden_size
self.bert = BertModel(config)
self.dropout = nn.Dropout(co... |
class XceptionA(nn.Module):
def __init__(self, num_classes=1000, norm_layer=nn.BatchNorm2d):
super(XceptionA, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(3, 8, 3, 2, 1, bias=False), norm_layer(8), nn.ReLU(True))
self.enc2 = Enc(8, 48, 4, norm_layer=norm_layer)
self.enc3 = E... |
def optuna_init_optimizers(self, methods, space, sampler='TPESampler', sampler_opts=None, **create_study_opts):
import optuna
if isinstance(sampler, str):
if (sampler_opts is None):
sampler_opts = {}
sampler = getattr(optuna.samplers, sampler)(**sampler_opts)
optuna.logging.set_v... |
class NATSpeechToTextDataset(SpeechToTextDataset):
def __getitem__(self, index: int) -> SpeechToTextDatasetItem:
has_concat = self.dataset_transforms.has_transform(ConcatAugment)
if has_concat:
concat = self.dataset_transforms.get_transform(ConcatAugment)
indices = concat.fin... |
def test_emission_matrix(model, X):
e = model._emission_matrix(X)
assert_array_almost_equal(e, [[[(- 4.3782), (- 3.6372)], [(- 7.2354), (- 2.7799)], [(- 21.0449), (- 4.2237)], [(- 24.8544), (- 5.2129)], [(- 1.9973), (- 4.6479)]], [[(- 42.9497), (- 7.7994)], [(- 1.5211), (- 3.9812)], [(- 17.7116), (- 3.9011)], [... |
class IBertConfig(PretrainedConfig):
model_type = 'ibert'
def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, init... |
class OwlViTProcessor(ProcessorMixin):
attributes = ['image_processor', 'tokenizer']
image_processor_class = 'OwlViTImageProcessor'
tokenizer_class = ('CLIPTokenizer', 'CLIPTokenizerFast')
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
if ('feature_extractor' in kwargs):
... |
def sample_mixture_normal(mean, logvar, pi):
(b, c, h, w, n_mixtures) = tuple(map(int, pi.size()))
pi = pi.view((((b * c) * h) * w), n_mixtures)
sampled_pi = torch.multinomial(pi, num_samples=1).view((- 1))
mean = mean.view((((b * c) * h) * w), n_mixtures)
mean = mean[(torch.arange((((b * c) * h) * ... |
def read_text(text_file):
for line in text_file:
parts = line.strip().split()
if (len(parts) < 1):
raise RuntimeError('Did not get enough columns; line {0} in {1}'.format(line, text_file.name))
elif (len(parts) == 1):
logger.warn('Empty transcript for utterance %s in ... |
class ONNXModel(BaseModel):
def __init__(self, model, **kwargs):
self._model = (model if (not isinstance(model, str)) else onnx.load(model, load_external_data=False))
self._model_path = (None if (not isinstance(model, str)) else model)
self.check_is_large_model()
if (self._is_large_m... |
def weights_from_ranking(rankings):
if (len(rankings) == 0):
assert False
if (type(rankings[0]) == type(0)):
rankings = [rankings]
rankings_num = len(rankings)
rankings_len = len(rankings[0])
assert all(((len(rankings[i]) == rankings_len) for i in range(rankings_num)))
total_scor... |
class AutoPipelineForImage2Image(ConfigMixin):
config_name = 'model_index.json'
def __init__(self, *args, **kwargs):
raise EnvironmentError(f'{self.__class__.__name__} is designed to be instantiated using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or `{self.__class__.... |
def get_colorize_data(sz: int, bs: int, crappy_path: Path, good_path: Path, random_seed: int=None, keep_pct: float=1.0, num_workers: int=8, stats: tuple=imagenet_stats, xtra_tfms=[]) -> ImageDataBunch:
src = ImageImageList.from_folder(crappy_path, convert_mode='RGB').use_partial_data(sample_pct=keep_pct, seed=rando... |
def get_name_bias_stats(links, attr_dict1, attr_dict2, cfg):
num_same = 0
num_close = 0
num_diff = 0
for ii in range(len(links)):
ent_name1 = get_name(links[ii][0], attr_dict1, cfg['dataset'])
ent_name2 = get_name(links[ii][1], attr_dict2, cfg['dataset'])
score = calc_edit_distan... |
def rewrite_logs(d):
new_d = {}
eval_prefix = 'eval_'
eval_prefix_len = len(eval_prefix)
for (k, v) in d.items():
if k.startswith(eval_prefix):
new_d[('eval/' + k[eval_prefix_len:])] = v
else:
new_d[('train/' + k)] = v
return new_d |
def match_function_multi_input_api_call(code):
ret = []
matches = re.finditer('\\([^)(]+,[^)(]+\\)', code)
for match in matches:
matched_code = match.group()
sc = code.split(matched_code)
if (len(sc) != 2):
continue
matched_code = matched_code[1:(- 1)]
for... |
def build_net(net_name, input_tfs, reuse=False):
net = None
if (net_name == fc_2layers_1024units.NAME):
net = fc_2layers_1024units.build_net(input_tfs, reuse)
elif (net_name == fc_3layers_512units_branch_inputs.NAME):
net = fc_3layers_512units_branch_inputs.build_net(input_tfs, reuse)
el... |
def ReadFileSL(x_axis, tthread, batchInterval, NUM_ITEMS, NUM_ACCESS, key_skewness, overlap_ratio, abort_ratio, isCyclic, complexity):
(w, h) = (2, len(x_axis))
y = [[] for _ in range(w)]
for abort_ratio in x_axis:
inputEvents = (tthread * batchInterval)
op_gs_path = getPathSL('OPGSA', input... |
def require_sentencepiece(test_case):
if (not is_sentencepiece_available()):
return unittest.skip('test requires SentencePiece')(test_case)
else:
return test_case |
def convert_to_npy(npz_file):
if (not os.path.isfile((npz_file[:(- 3)] + 'npy'))):
a = np.load(npz_file)['data']
np.save((npz_file[:(- 3)] + 'npy'), a) |
class SharedValue(object):
def __init__(self, data) -> None:
sc = OrcaContext.get_spark_context()
self.broadcast_data = sc.broadcast(data)
self._value = None
def value(self):
self._value = self.broadcast_data.value
return self._value
def unpersist(self):
self.... |
def est_accuracy(mal_visible, t):
args = gv.args
delta_other_prev = None
if (len(mal_visible) >= 1):
mal_prev_t = mal_visible[(- 1)]
print(('Loading from previous iteration %s' % mal_prev_t))
delta_other_prev = np.load((gv.dir_name + ('ben_delta_t%s.npy' % mal_prev_t)), allow_pickle=... |
class ParameterScheduler(_Scheduler):
def __init__(self, step=0, mode='train', **schedulers):
super(ParameterScheduler, self).__init__(step)
self.schedulers = schedulers
self.mode = mode
def train(self):
self.mode = 'train'
for scheduler in self.schedulers.values():
... |
class Albadi2018(dataset.Dataset):
name = 'albadi2018'
url = '
hash = '7f7d87384b4b715655ec0e2d329bc234bbc965ad116290f2e2d0b11e26e272b3'
files = [{'name': 'albadi2018ar_train.csv', 'language': 'ar', 'type': 'training', 'platform': 'twitter'}, {'name': 'albadi2018ar_test.csv', 'language': 'ar', 'type': '... |
class PairedDataset(Dataset):
def __init__(self, files_a: Tuple[str], files_b: Tuple[str], transform_fn: Callable, normalize_fn: Callable, corrupt_fn: Optional[Callable]=None, preload: bool=True, preload_size: Optional[int]=0, verbose=True):
assert (len(files_a) == len(files_b))
self.preload = prelo... |
class Preprocessor():
def __init__(self, config_dir, save_config_dir=None, verbose=True):
self.config_dir = config_dir
self.verbose = verbose
(self.vocab, self.vocab_dict) = self.__load_list_file(FILE_VOCAB, offset=1, verbose=verbose)
(self.tags, self.tags_dict) = self.__load_list_fi... |
def draw_circle_edge(ax: matplotlib.axes.Axes, v_coor: List[Tuple[(float, float)]], v_size: list, e_list: List[Tuple[(int, int)]], e_color: list, e_fill_color: list, e_line_width: list):
n_v = len(v_coor)
(line_paths, arc_paths, vertices) = hull_layout(n_v, e_list, v_coor, v_size)
for (eidx, lines) in enume... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.