code stringlengths 101 5.91M |
|---|
def adapt_bn(data, model, cfg):
model = bn_helper.configure_model(model, eps=1e-05, momentum=0.1, reset_stats=False, no_stats=False)
for _ in range(cfg.ITER):
model(**data)
print('Adaptation Done ...')
model.eval()
return model |
class MixedInt8TestTraining(BaseMixedInt8Test):
def setUp(self):
self.model_name = 'facebook/opt-350m'
super().setUp()
def test_training(self):
if (version.parse(importlib_metadata.version('bitsandbytes')) < version.parse('0.37.0')):
return
model = AutoModelForCausalL... |
('generate-codes')
def main(dataset: str, output: str, model: str, shards: SplitIndices=None, batch_size: int=None, splits: List[str]=None, profile_batch_id: int=None, use_gpu: bool=True):
import torch
from viewformer.utils.torch import load_model
device = ('cpu' if ((not use_gpu) or (torch.cuda.device_coun... |
def validate_flags_or_throw(bert_config):
if ((not FLAGS.do_train) and (not FLAGS.do_predict)):
raise ValueError('At least one of `do_train` or `do_predict` must be True.')
if FLAGS.do_train:
if (not FLAGS.train_file):
raise ValueError('If `do_train` is True, then `train_file` must b... |
class UniformFofModel(LogitModel):
def __init__(self, model_id, D=None, vvv=False):
LogitModel.__init__(self, model_id, bounds=((1, 1),), D=D, vvv=vvv)
self.model_type = 'uniform_fof'
self.model_short = 'uf'
self.D['has'] = (self.D.fof > 0)
self.D['choose'] = (1 * ((self.D['h... |
class DecoderType(Enum):
PYAV = 'pyav'
TORCHVISION = 'torchvision'
FRAME = 'frame'
DUMB = 'dumb' |
class SpotPaths():
def from_path(cls, data_path: str, path_prefix: str='', dataset: SpotDatasets=SpotDatasets.TENNIS) -> SpotPaths:
if g_pathmgr.isfile(data_path):
if (Path(data_path).suffix == '.json'):
return SpotPaths.from_json(data_path, path_prefix)
raise NotImpl... |
def is_valid_size_dict(size_dict):
if (not isinstance(size_dict, dict)):
return False
size_dict_keys = set(size_dict.keys())
for allowed_keys in VALID_SIZE_DICT_KEYS:
if (size_dict_keys == allowed_keys):
return True
return False |
class Verification(object):
def __init__(self, dim, row_pointers, column_index, degrees, partPtr, part2Node, partSize, dimWorker, warpPerBlock):
self.row_pointers = row_pointers
self.column_index = column_index
self.degrees = degrees
self.partPtr = partPtr
self.part2Node = pa... |
class ParallelModeOptimization(Optimization):
def __init__(self):
name = 'parallel_mode'
group = 'parallel_mode'
is_tunable = False
super().__init__(name, group, is_tunable)
def tune(self, model_context, config=None, strategy=None, apply_transform=True, time_limit=None):
... |
def _partitioned_variable_assign(partitioned_var, new_value):
axis = (0 if (len(partitioned_var) == 1) else _determine_partitioned_axis(partitioned_var))
partition_sizes = np.array([partition.get_shape()[axis] for partition in partitioned_var])
new_partitioned_values = array_ops.split(new_value, ops.convert... |
def master_only(func):
(func)
def wrapper(*args, **kwargs):
(rank, _) = get_dist_info()
if (rank == 0):
return func(*args, **kwargs)
return wrapper |
class parsingNet(torch.nn.Module):
def __init__(self, size=(288, 800), pretrained=True, backbone='50', cls_dim=(37, 10, 4), use_aux=False):
super(parsingNet, self).__init__()
self.size = size
self.w = size[0]
self.h = size[1]
self.cls_dim = cls_dim
self.use_aux = use_... |
class ConvBertForTokenClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def create_dummy_object(name, type='pt'):
_pretrained = ['ConfigForCausalLM', 'ForConditionalGeneration', 'ForMaskedLM', 'ForMultipleChoice', 'ForQuestionAnswering', 'ForSequenceClassification', 'ForTokenClassification', 'Model', 'Tokenizer']
assert (type in ['pt', 'tf', 'sentencepiece', 'tokenizers', 'flax'])
... |
def dump_all_entities(examples, out_path, id2text: dict):
id2entity = {}
relations = set()
for ex in examples:
head_id = ex['head_id']
relations.add(ex['relation'])
if (head_id not in id2entity):
id2entity[head_id] = {'entity_id': head_id, 'entity': ex['head'], 'entity_de... |
class ResNet18WithEmbeddingHead(nn.Module):
def __init__(self, num_classes, emb_dim=128, pretrained=True):
super(ResNet18WithEmbeddingHead, self).__init__()
self.model_resnet = models.resnet18(pretrained=pretrained)
self.num_ftrs = self.model_resnet.fc.in_features
self.model_resnet.f... |
def add_model_ema_configs(_C):
_C.MODEL_EMA = type(_C)()
_C.MODEL_EMA.ENABLED = False
_C.MODEL_EMA.DECAY = 0.999
_C.MODEL_EMA.DEVICE = ''
_C.MODEL_EMA.USE_EMA_WEIGHTS_FOR_EVAL_ONLY = False
_C.MODEL_EMA.YOLOX = False |
class DenseBlock(nn.ModuleDict):
_version = 2
def __init__(self, num_layers, num_input_features, bn_size, growth_rate, norm_layer=nn.ReLU, drop_rate=0.0, memory_efficient=False):
super(DenseBlock, self).__init__()
for i in range(num_layers):
layer = DenseLayer((num_input_features + (... |
def fwd2bwd(fwd_flow, fwd_flow_conf):
(_, _, h, w) = fwd_flow.shape
bwd_flow = np.zeros((1, 2, h, w))
flags = np.zeros((1, 2, h, w))
from scipy import interpolate
x_coordinates = []
y_coordinates = []
flow_x_values = []
flow_y_values = []
for i in range(h):
for j in range(w):... |
_module()
class YOLOXPAFPN(BaseModule):
def __init__(self, in_channels, out_channels, num_csp_blocks=3, use_depthwise=False, upsample_cfg=dict(scale_factor=2, mode='nearest'), conv_cfg=None, norm_cfg=dict(type='BN', momentum=0.03, eps=0.001), act_cfg=dict(type='Swish'), init_cfg=dict(type='Kaiming', layer='Conv2d',... |
class Node():
type = NodeType.UNKNOWN
addr = ''
name = None
error = False
def __init__(self, type, addr=addr):
self.type = type
self.addr = addr
try:
self.name = socket.gethostbyaddr(addr)[0]
except socket.error as e:
self.name = None
def _... |
class DatasetConfig():
def __init__(self, file_pattern, split_sizes):
self.file_pattern = file_pattern
self.split_sizes = split_sizes |
class MixtureOfLaplaceNLLLoss(nn.Module):
def __init__(self, eps: float=1e-06, reduction: str='mean') -> None:
super(MixtureOfLaplaceNLLLoss, self).__init__()
self.reduction = reduction
self.nll_loss = LaplaceNLLLoss(eps=eps, reduction='none')
def forward(self, pred: torch.Tensor, target... |
def sanitize_html(txt: Union[(str, TokenWithId)]) -> str:
if isinstance(txt, TokenWithId):
txt = txt.token
return txt.replace('<', '<').replace('>', '>') |
class _VIPSReader():
has_levels = True
def __init__(self, path: str, mpp: Optional[float]=None, *, cache_kw: Optional[Dict[(str, Any)]]=None, ignore_missing_mpp: bool=False, pad_missing: bool=True, loaded_image: Optional['vips.Image']=None, use_bounds: bool=False, transforms: Optional[List[int]]=None) -> None:
... |
class MBartForSequenceClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def validate() -> None:
val_losses = []
i_val_step = 0
for input in cutpaste_val_loader:
i_val_step += 1
loss = val_step(input)
val_losses.append(loss.item())
if (i_val_step >= config.val_steps):
break
validation_loss = np.mean(val_losses)
log_msg = f'Vali... |
class TFAlbertForMaskedLM():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
def parse_affine_component(component, line, line_buffer):
assert ('<LinearParams>' in line)
pairs = dict(re.findall('(<\\w+>) ([\\w.-]+)', line))
weights = parse_weights(line_buffer)
bias = parse_bias(next(line_buffer))
matrix = np.concatenate([weights, bias.T], axis=1)
(_, filename) = tempfile.... |
def ReadStats(pron_stats_handle):
stats = defaultdict(list)
for line in pron_stats_handle.readlines():
splits = line.strip().split()
if (len(splits) == 0):
continue
if (len(splits) < 2):
raise Exception((('Invalid format of line ' + line) + ' in stats file.'))
... |
class HTMLParser(_HTMLParser):
def clean(self, html):
html = decode_utf8(html)
html = html.replace('/>', ' />')
html = html.replace(' />', ' />')
html = html.replace('<!', '<!')
html = html.replace('<!DOCTYPE', '<!DOCTYPE')
html = html.replace('<!doctype', '... |
def is_short(w):
return (is_short_syllable(w[(- 3):]) and (len([ch for ch in w[:(- 3)] if (ch in VOWELS)]) == 0)) |
class VeRi(BaseImageDataset):
dataset_dir = 'VeRi'
def __init__(self, root='', verbose=True, **kwargs):
super(VeRi, self).__init__()
self.dataset_dir = osp.join(root, self.dataset_dir)
self.train_dir = osp.join(self.dataset_dir, 'image_train')
self.query_dir = osp.join(self.datas... |
def get_coord_map(FILENAME):
lab_name = FILENAME.replace('JPEGImages', 'SegmentationObject').replace('.jpg', '.png')
annot_name = FILENAME.replace('JPEGImages', 'Annotations').replace('.jpg', '.xml')
img = read_lab(lab_name)
img[(img == 255)] = 0
lab = parse_xml(annot_name)
lab = np.int32(lab)
... |
class UploadCommand(setuptools.Command):
description = 'Build and publish the package.'
user_options = []
def status(s):
print('\x1b[1m{0}\x1b[0m'.format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
here =... |
def dropout_train_res(model, train_mode=True):
for m in model.modules():
if hasattr(m, 'dropout_train'):
m.dropout_train = train_mode |
_cache()
def _get_gpu_extra_compile_args():
if torch.cuda.is_available():
return []
else:
return ['-arch=compute_60'] |
def test_tune_hyperparam_randomsearch(df_iris: pd.DataFrame) -> None:
df_iris = df_iris[df_iris['species'].isin(['versicolor', 'virginica'])]
X = ['sepal_length', 'sepal_width', 'petal_length']
y = 'species'
X_types = {'continuous': X}
sk_X = df_iris[X].values
sk_y = df_iris[y].values
scorin... |
class FakeEasyDLClient(object):
def get_task(self):
pass
def report_task_result(self):
pass |
class NN(Base):
def __init__(self, args, c_in, c_out, height, width, nn_type, kernel=3):
super().__init__()
Conv2dAct = Conv2dReLU
n_channels = args.n_channels
if (nn_type == 'shallow'):
if (args.network1x1 == 'standard'):
conv1x1 = Conv2dAct(n_channels, n... |
class FabiansUNet(SegmentationNetwork):
use_this_for_2D_configuration = .0
use_this_for_3D_configuration = .0
default_blocks_per_stage_encoder = (1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4)
default_blocks_per_stage_decoder = (1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
default_min_batch_size = 2
def __init__(self, input... |
def test_ce_loss():
from mmdet.models import build_loss
with pytest.raises(AssertionError):
loss_cfg = dict(type='CrossEntropyLoss', use_mask=True, use_sigmoid=True, loss_weight=1.0)
build_loss(loss_cfg)
loss_cls_cfg = dict(type='CrossEntropyLoss', use_sigmoid=False, class_weight=[0.8, 0.2],... |
def check(P):
filename_with_today_date = True
assert (P.num_shots_global == 0)
return filename_with_today_date |
class MaxLengthCriteria(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class PositionalLabel():
def __init__(self, labeled_sections: List[Tuple[(str, Tuple[(float, float)])]]):
if (not labeled_sections):
raise ValueError('Sections must be specified.')
if any(((range is None) for (label, range) in labeled_sections)):
raise ValueError('Range must ... |
class AtariPreprocessing(object):
def __init__(self, environment, frame_skip=4, terminal_on_life_loss=False, screen_size=84):
if (frame_skip <= 0):
raise ValueError('Frame skip should be strictly positive, got {}'.format(frame_skip))
if (screen_size <= 0):
raise ValueError('T... |
def create_tmp_dir_multi_session():
ignore_git_pattern = shutil.ignore_patterns(str((path_data_multi_sessions_contrasts_source / '.git')))
remove_tmp_dir()
Path(path_temp).mkdir()
if Path(path_data_multi_sessions_contrasts_source).exists():
shutil.copytree(path_data_multi_sessions_contrasts_sour... |
def main_upper(x_minus, x_plus, y_minus, y_plus, plot=False, num=0, print_info=True):
if print_info:
print('4th orthant upper: using third.main_lower function')
x_minus_new = (- x_plus)
x_plus_new = (- x_minus)
(a, b, c) = third.main_lower(x_minus_new, x_plus_new, y_minus, y_plus, print_info=pri... |
def _load_groundtruth(filepath):
assert os.path.isfile(filepath)
xmldoc = minidom.parse(filepath)
itemlist = xmldoc.getElementsByTagName('file')
assert (len(itemlist) == 1)
num_frames = None
for e in itemlist[0].getElementsByTagName('attribute'):
if (e.attributes['name'].value == 'NUMFRA... |
def test_retina_head_forward():
retina_model = retinanet_config()
s = 128
feats = [torch.rand(1, retina_model.in_channels, (s // (2 ** (i + 2))), (s // (2 ** (i + 2)))) for i in range(len(retina_model.anchor_generator.strides))]
wrap_model = WrapFunction(retina_model.forward)
ort_validate(wrap_model... |
def _attempt_creation(entity_name, type_name, type_dict, provided_kwargs, additional_kwargs):
if (type_name not in type_dict):
raise KeyError(f"{entity_name.title()} '{type_name}' is not registered")
entity_type = type_dict[type_name]
return entity_type(**additional_kwargs, **_remove_type_key(provid... |
class IBNResUnit(nn.Module):
def __init__(self, in_channels, out_channels, stride, conv1_ibn):
super(IBNResUnit, self).__init__()
self.resize_identity = ((in_channels != out_channels) or (stride != 1))
self.body = IBNResBottleneck(in_channels=in_channels, out_channels=out_channels, stride=st... |
class CodeGenMacroMathjax(CodeGenMathjax):
def __init__(self):
super().__init__(ParserTypeEnum.MACROMATHJAX)
def init_type(self, type_walker, func_name):
super().init_type(type_walker, func_name)
self.code_frame.pre_str = self.pre_str
self.code_frame.post_str = self.post_str
... |
def round_robin_strategy(num_tasks, last_task=None):
if (last_task is None):
return 0
return ((last_task + 1) % num_tasks) |
class Sudoku(Environment[State]):
def __init__(self, generator: Optional[Generator]=None, reward_fn: Optional[RewardFn]=None, viewer: Optional[Viewer[State]]=None):
if (generator is None):
file_path = os.path.dirname(os.path.abspath(__file__))
database_file = DATABASES['mixed']
... |
def iou(box1, box2):
box1 = np.asarray(box1, np.float32)
box2 = np.asarray(box2, np.float32)
intersection_area = area(intersect(box1, box2))
union_area = ((area(box1) + area(box2)) - intersection_area)
return (intersection_area / union_area) |
class TestQuantization(unittest.TestCase):
def setUp(self):
logging.disable(logging.CRITICAL)
def tearDown(self):
logging.disable(logging.NOTSET)
((not torch.cuda.is_available()), 'test requires a GPU')
def test_quantization(self):
with contextlib.redirect_stdout(StringIO()):
... |
def staticTFTest(data, gt_data):
for couple in gt_data.keys():
if (data[couple] is None):
msg = ('Tf is None for couple %s' % '->'.join(couple))
return (False, msg)
if (any((abs((np.array(data[couple][0]) - np.array(gt_data[couple][0]))) > 1e-05)) or any((abs((np.array(data[c... |
def metadata2dict(filename, header, key_index=0):
d = {}
with open(filename, 'rt') as f:
for row in csv.reader(f):
row = [x.strip().strip('"') for x in row]
c = row[key_index]
d[c] = dict(zip(header, row))
return d |
class TestTemplatePointwiseAttention(unittest.TestCase):
def test_shape(self):
batch_size = consts.batch_size
n_seq = consts.n_seq
c_t = consts.c_t
c_z = consts.c_z
c = 26
no_heads = 13
n_res = consts.n_res
inf = .0
tpa = TemplatePointwiseAtten... |
def strong_aug_pixel(p=0.5):
print('[DATA]: strong aug pixel')
from albumentations import Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue, MultiplicativeNoise, IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, RandomBrightnessContrast, IAAPiecewiseAffine, IAA... |
def create_inception_graph(pth):
with tf.gfile.FastGFile(pth, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='FID_Inception_Net') |
def categorical_gru_policy_tf_ppo_benchmarks():
iterate_experiments(categorical_gru_policy, STATE_ENV_SET, seeds=_seeds) |
class DataInjector(object):
def __init__(self, def_path, data_path):
self.def_path = def_path
self.data_path = data_path
self.did_use_pb = False
self.params = None
self.load()
def load(self):
if has_pycaffe():
self.load_using_caffe()
else:
... |
def get_dueling_dqn_agent(network, environment=None, states=None, actions=None, max_episode_timesteps=None, batch_size=32, learning_rate=0.0001, horizon=1, discount=0.99, memory=200000, device='gpu'):
if (environment != None):
agent = Agent.create(agent='dueling_dqn', environment=environment, max_episode_ti... |
class TFXLMRobertaForCausalLM(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def save_dict(log_path, dic, name):
path = os.path.join(log_path, ('%s.json' % name))
f = open(path, 'w')
json.dump(vars(dic), f)
f.close()
path = os.path.join(log_path, ('%s.txt' % name))
f = open(path, 'w')
args_str = [('%s = %s' % (key, value)) for (key, value) in vars(dic).items()]
f... |
class dsRLA_MobileNetV2(nn.Module):
def __init__(self, num_classes: int=1000, width_mult: float=1.0, rla_channel: int=32, inverted_residual_setting: Optional[List[List[int]]]=None, round_nearest: int=8, block: Optional[Callable[(..., nn.Module)]]=None, norm_layer: Optional[Callable[(..., nn.Module)]]=None, ECA=Fals... |
class TFBaseModelOutputWithPooling(ModelOutput):
last_hidden_state: tf.Tensor = None
pooler_output: tf.Tensor = None
hidden_states: Optional[Tuple[tf.Tensor]] = None
attentions: Optional[Tuple[tf.Tensor]] = None |
def resnet14_cub(num_classes=200, **kwargs):
return get_resnet(num_classes=num_classes, blocks=14, model_name='resnet14_cub', **kwargs) |
def get_reward_stats(lst):
lst = torch.stack(lst)
(v_min, v_max, v_mean) = (lst.min(), lst.max(), torch.mean(lst))
return (v_min, v_max, v_mean) |
def get_sent_paragraph(span):
doc = span.doc
pars = span.doc._.paragraphs
for (idx, s) in enumerate(doc._.sentences):
if (s == span):
return pars[idx]
return 0 |
class SpatialDropout2D(KerasLayer):
def __init__(self, p=0.5, dim_ordering='th', input_shape=None, **kwargs):
super(SpatialDropout2D, self).__init__(None, float(p), dim_ordering, (list(input_shape) if input_shape else None), **kwargs) |
class PPO():
def __init__(self, state_dim, action_dim, action_std, lr, betas, gamma, K_epochs, eps_clip):
self.lr = lr
self.betas = betas
self.gamma = gamma
self.eps_clip = eps_clip
self.K_epochs = K_epochs
self.policy = ActorCritic(state_dim, action_dim, action_std).... |
def get_cs(e_0=100, z=74):
with open(os.path.join(data_path, 'cs/grid.csv'), 'r') as csvfile:
r = csv.reader(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
t = next(r)
e_e = np.array([float(a) for a in t[0].split(',')])
log_e_e = np.log10(e_e)
t = next(r)
... |
def process_one_img(file, im):
if (im.mode == 'RGB'):
im.thumbnail((400, 400), Image.ANTIALIAS)
im.save((file + '.jpg'))
os.remove(file)
else:
im = im.convert('RGB')
im.thumbnail((400, 400), Image.ANTIALIAS)
im.save((file + '.jpg'))
os.remove(file) |
def kronecker(matrix1, matrix2):
return torch.ger(matrix1.view((- 1)), matrix2.view((- 1))).reshape(*(matrix1.size() + matrix2.size())).permute([0, 2, 1, 3]).reshape((matrix1.size(0) * matrix2.size(0)), (matrix1.size(1) * matrix2.size(1))) |
def test_digits_cosine_naive_object():
model1 = FacilityLocationSelection(100)
model2 = GraphCutSelection(100)
model = MixtureSelection(100, [model1, model2], [1.0, 0.3], metric='cosine', optimizer=NaiveGreedy(random_state=0))
model.fit(X_digits)
assert_array_equal(model.ranking, digits_cosine_ranki... |
def writeWorldDescr(output):
if options.noStaticInit:
output.write('const char* CxxTest::RealWorldDescription::_worldName;\n')
else:
output.write('const char* CxxTest::RealWorldDescription::_worldName = "cxxtest";\n') |
def get_num_frames(video_frame_dir):
max_frame = (- 1)
for img_file in os.listdir(video_frame_dir):
if img_file.endswith('.jpg'):
frame = int(os.path.splitext(img_file)[0])
max_frame = max(frame, max_frame)
return (max_frame + 1) |
def get_feat_dim(feat_dir):
if (feat_dir is None):
return 0
stdout_val = get_command_stdout('feat-to-dim --print-args=false scp:{data}/feats.scp -'.format(data=feat_dir))
feat_dim = int(stdout_val)
return feat_dim |
def wResUnit(data, num_filter, stride, dilate, projection, bottle_neck, dropout=0, momentum=0.9, eps=1e-05, use_global_stats=False, name=None, lr_mult=1, reuse=None, **kwargs):
assert (name is not None)
x = BNRelu(data, fix_gamma=False, momentum=momentum, eps=eps, use_global_stats=use_global_stats, name=(('bn' ... |
_function('min')
class AutogradMin(AutogradFunction):
def forward(ctx, *args, **kwargs):
assert (len(args) >= 1)
if (len(args) == 1):
(input,) = args
dim = kwargs.get('dim', None)
else:
assert (len(args) == 2)
assert ('dim' not in kwargs)
... |
.parametrize('a_val, b_val, x_val, y_val, vector', [(1.0, 1.0, 1.0, 1.0, [10.0, 20.0]), (5.0, 10.0, (- 2.0), 5.0, [0.0, (- 1.0)]), (0.0, 0.0, 1.1, 0.02, [0.0, 0.0]), ((- 2.2), (- 1.5), (- 12.3), 34.8, [2.2, 5.3]), ((- 1.5), 0.0, (- 0.002), 4.93, [0.1, (- 0.02)])])
def test_hessian_vector_product_2x2_non_diagonal(a_val,... |
def insert(text, vocab, n_max_tokens=3):
tokens = text.split()
n_insert_token = random.randint(1, n_max_tokens)
for _ in range(n_insert_token):
insert_token_idx = random.randint(0, (len(tokens) - 1))
insert_token = random.choice(vocab)
tokens = ((tokens[:insert_token_idx] + [insert_t... |
class FeatureLabelPreprocessing(Preprocessing):
def __init__(self, feature_transformer, label_transformer, bigdl_type='float'):
super(FeatureLabelPreprocessing, self).__init__(bigdl_type, feature_transformer, label_transformer) |
.parametrize('t', [t0, t1, t2, t3, t4])
def test_sort(t):
print()
o = []
ray_len = len(t)
j = 0
while (j < (len(t) - 1)):
offset = 1
if (t[j] is None):
j += 1
continue
dn = t[j][0]
clear_self = False
while (((j + offset) < ray_len) and ... |
class Logger():
def __init__(self, basedir):
self.logfile = os.path.join(basedir, 'log.txt')
def log(self, msg, out=False):
with open(self.logfile, 'a+') as logfile:
logfile.write(msg)
logfile.write('\n')
if out:
print(msg)
def logo(self, msg):
... |
def ILP_protocol_w_compression(reference_summary: str, sent_units: List[str], compression: List[dict], min_word_limit=30, max_word_limit=40, step=3):
print('Compression')
constraint_list = []
ref_toks = reference_summary.split(' ')
ref_toks = [x.lower() for x in ref_toks]
ref_toks_set = list(set(ref... |
class TFAutoModelForQuestionAnswering(object):
def __init__(self):
raise EnvironmentError('TFAutoModelForQuestionAnswering is designed to be instantiated using the `TFAutoModelForQuestionAnswering.from_pretrained(pretrained_model_name_or_path)` or `TFAutoModelForQuestionAnswering.from_config(config)` method... |
def _mark_lines(linewavs, wavemin, wavemax, thisax, lams, spec):
ylims = thisax.get_ylim()
yspan = (ylims[1] - ylims[0])
for linewav in linewavs:
spindx = numpy.argmin(numpy.fabs((linewav - lams)))
ylevel = numpy.nanmin(spec[(spindx - 2):(spindx + 3)])
thisax.plot([(linewav - _LAMBDA... |
class Regularizer(object):
def __init__(self, l1=0.0, l2=0.0, maxnorm=0.0, l2norm=False, frobnorm=False, ignored_prefixes=[]):
ignored_prefixes = set(ignored_prefixes)
self.__dict__.update(locals())
def max_norm(self, p, maxnorm):
if (maxnorm > 0):
norms = T.sqrt(T.sum(T.sqr(... |
class VOC12ImageDataset(Dataset):
def __init__(self, img_name_list_path, voc12_root, resize_long=None, rescale=None, img_normal=TorchvisionNormalize(), hor_flip=False, crop_size=None, crop_method=None, to_torch=True):
self.img_name_list = load_img_name_list(img_name_list_path)
self.voc12_root = voc1... |
class Caffe2Tracer():
def __init__(self, cfg, model, inputs):
assert isinstance(cfg, CN), cfg
assert isinstance(model, torch.nn.Module), type(model)
if ('EXPORT_CAFFE2' not in cfg):
cfg = add_export_config(cfg)
self.cfg = cfg
self.model = model
self.inputs... |
class Seq2SeqSequenceClassifierOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTenso... |
def test_register_model() -> None:
register_model('dt', classification_cls=DecisionTreeClassifier, regression_cls=DecisionTreeRegressor)
classification = get_model('dt', 'classification')
regression = get_model('dt', 'regression')
assert isinstance(classification, DecisionTreeClassifier)
assert isin... |
def ewc_loss(params: Params, model: nn.Module, grads=None):
try:
losses = []
for (n, p) in model.named_parameters():
n = n.replace('.', '__')
mean = getattr(model, '{}_mean'.format(n))
fisher = getattr(model, '{}_fisher'.format(n))
losses.append((fishe... |
_model
def tf_efficientnetv2_m_in21ft1k(pretrained=False, **kwargs):
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnetv2_m('tf_efficientnetv2_m_in21ft1k', pretrained=pretrained, **kwargs)
return model |
def get_plane_params_in_global(planes, camera_info):
tran = camera_info['position']
rot = camera_info['rotation']
start = (np.ones((len(planes), 3)) * tran)
end = (planes * np.array([1, (- 1), (- 1)]))
end = ((quaternion.as_rotation_matrix(rot) end.T).T + tran)
a = end
b = (end - start)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.