code stringlengths 101 5.91M |
|---|
def foreground_mean(filename):
with open(filename, 'r') as f:
res = json.load(f)
class_ids = np.array([int(i) for i in res['results']['mean'].keys() if (i != 'mean')])
class_ids = class_ids[(class_ids != 0)]
class_ids = class_ids[(class_ids != (- 1))]
class_ids = class_ids[(class_ids != 99)]... |
def export_sentence_embedding():
import os
pheme_data_output_path = os.path.join(os.path.dirname(__file__), '..', '..', 'output', 'elmo', 'pheme_source_tweet_corpus.txt')
pheme_data_embedding_output = os.path.join(os.path.dirname(__file__), '..', '..', 'output', 'elmo', 'pheme_source_tweet_corpus_elmo_embed... |
def setup_dist(rank, world_size, master_port=None):
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = ('12354' if (master_port is None) else str(master_port))
dist.init_process_group('nccl', rank=rank, world_size=world_size)
torch.cuda.set_device(rank) |
def copy_files_and_create_dirs(files: List[Tuple[(str, str)]]) -> None:
for file in files:
target_dir_name = os.path.dirname(file[1])
if (not os.path.exists(target_dir_name)):
os.makedirs(target_dir_name)
shutil.copyfile(file[0], file[1]) |
def load_cifar10_data(datadir):
transform = transforms.Compose([transforms.ToTensor()])
cifar10_train_ds = CIFAR10_truncated(datadir, train=True, download=True, transform=transform)
cifar10_test_ds = CIFAR10_truncated(datadir, train=False, download=True, transform=transform)
(X_train, y_train) = (cifar1... |
def _hash_file(fpath, algorithm='sha256', chunk_size=65535):
if ((algorithm == 'sha256') or ((algorithm == 'auto') and (len(hash) == 64))):
hasher = hashlib.sha256()
else:
hasher = hashlib.md5()
with open(fpath, 'rb') as fpath_file:
for chunk in iter((lambda : fpath_file.read(chunk_s... |
def deform_conv_function(input, offset, weight, stride=1, padding=0, dilation=1, deform_groups=1, im2col_step=64):
if ((input is not None) and (input.dim() != 4)):
raise ValueError('Expected 4D tensor as input, got {}D tensor instead.'.format(input.dim()))
f = DeformConvFunction(_pair(stride), _pair(pad... |
class SparsityStats(object):
__sparsity_ignore__ = ()
def sparsity(self, **kwargs):
raise NotImplementedError('Derived classes must implement a method to estimate sparsity.') |
def load_image_single(f_path):
im = Image.open(f_path).convert('RGB')
width_side = im.size[0]
new_h = (width_side / 2)
im = im.crop((0, ((im.size[1] / 2) - (new_h / 2)), width_side, ((im.size[1] / 2) + (new_h / 2))))
im = im.resize((image_size[0], image_size[1]), Image.LANCZOS)
in_ = np.array(im... |
class Screen():
screen = None
font = None
y_pos = 0
x_pos = 0
def setup_screen(self):
pygame.display.set_caption('OpenBot keyboard controller')
self.font = pygame.font.Font(None, 32)
self.screen = pygame.display.set_mode([1280, 760], pygame.RESIZABLE)
self.screen.fill... |
def collate_to_max_length_with_id(batch: List[List[torch.Tensor]], max_len: int=None, fill_values: List[float]=None) -> List[torch.Tensor]:
tokens_size = [sample[(- 1)] for sample in batch]
srcs = [sample[(- 2)] for sample in batch]
ids = [sample[(- 3)] for sample in batch]
batch = [sample[:(- 3)] for s... |
def get_scheduler(config):
name = 'iterative'
if (config.start_step == config.end_step):
name = 'oneshot'
return SCHEDULERS[name](config) |
def _log_parameters(logger: Callable, params: dict):
logger(('\n\t' + ', \n\t'.join([f'{x[0]}: {x[1]}' for x in params.items()]))) |
def load_svhn(dataset_dir, split='train'):
data_dir = osp.join(dataset_dir, SVHN[split])
n_max = (25000 if (split == 'train') else 9000)
return read_image_list(data_dir, n_max=n_max) |
class SubMConvFunction(Function):
def forward(ctx, features, filters, indice_pairs, indice_pair_num, num_activate_out):
ctx.save_for_backward(indice_pairs, indice_pair_num, features, filters)
return ops.indice_conv(features, filters, indice_pairs, indice_pair_num, num_activate_out, False, True)
... |
def _weights_init(m):
if isinstance(m, nn.Conv2d):
torch.nn.init.xavier_uniform_(m.weight)
if (m.bias is not None):
torch.nn.init.zeros_(m.bias)
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m... |
def get_few_shot_cot_prompt(dataset_key) -> str:
data = load_few_shot_cot_prompts()
if (dataset_key not in data):
raise KeyError('Few-shot-CoT prompts are not available for dataset `{}`'.format(dataset_key))
return data[dataset_key]['prompt'] |
class Hypothesis(object):
def __init__(self, tokens, log_probs, hidden_state, cell_state, coverage):
self.tokens = tokens
self.log_probs = log_probs
self.hidden_state = hidden_state
self.cell_state = cell_state
self.coverage = coverage
def extend(self, token, log_prob, hi... |
class ComputeTDErrorMixin():
def __init__(self):
def compute_td_error(obs_t, act_t, rew_t, obs_tp1, done_mask, importance_weights):
input_dict = self._lazy_tensor_dict({SampleBatch.CUR_OBS: obs_t, SampleBatch.ACTIONS: act_t, SampleBatch.REWARDS: rew_t, SampleBatch.NEXT_OBS: obs_tp1, SampleBatch.... |
class BasicBlockNoSkip(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1, downsample=None):
super(BasicBlockNoSkip, self).__init__()
self.conv1 = conv3x3(in_planes, planes, stride=stride)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = conv3x3(planes, planes... |
def fs_cothub_bbh_match_answer(task_data, response):
ans_line = response.split('answer is ')
if (len(ans_line) == 1):
return (False, response)
else:
ans = ans_line[(- 1)].strip()
if task_data['options']:
options = ['(A)', '(B)', '(C)', '(D)', '(E)', '(F)', '(G)', '(H)', '(I)', '(... |
def iresnet50(pretrained=False, **kwargs):
model = iResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
os.makedirs(default_cache_path, exist_ok=True)
model.load_state_dict(torch.load(download_from_url(model_urls['iresnet50'], root=default_cache_path)))
return model |
class TestCommon(unittest.TestCase):
def test_move_element_to_front(self):
f = common.move_element_to_front
self.assertEqual(f([1, 2, 3, 4], 0), [1, 2, 3, 4])
self.assertEqual(f([1, 2, 3, 4], 1), [1, 2, 3, 4])
self.assertEqual(f([1, 2, 3, 4], 2), [2, 1, 3, 4])
self.assertEqua... |
def save_load_code(data_size, batch_size):
backend = ('nccl' if torch.cuda.is_available() else 'gloo')
res = atorch.init_distributed(backend, set_cuda_device_using_local_rank=True)
if (not res):
raise Exception('init failed')
model_context = create_model_context(data_size=data_size, batch_size=b... |
class ReplayBuffer(metaclass=abc.ABCMeta):
def __init__(self, env_spec, size_in_transitions, time_horizon):
del env_spec
self._current_size = 0
self._current_ptr = 0
self._n_transitions_stored = 0
self._time_horizon = time_horizon
self._size_in_transitions = size_in_t... |
class MicroCodeGen():
def __init__(self):
pass
def gen_micro_ops_list_from_bytes(self, model_tag, op_src_path_list, op_class_name_list, jinja_file_name, output_path):
cwd = os.path.dirname(__file__)
j2_env = Environment(loader=FileSystemLoader(cwd), trim_blocks=True, keep_trailing_newlin... |
def analyze(df):
print()
cols = df.columns.values
total = float(len(df))
print('{} rows'.format(int(total)))
for col in cols:
uniques = df[col].unique()
unique_count = len(uniques)
if (unique_count > 100):
print('** {}:{} ({}%)'.format(col, unique_count, int(((uni... |
class WarmupCosineWithWarmupRestartsSchedule(WarmupCosineWithHardRestartsSchedule):
def __init__(self, warmup=0.002, t_total=(- 1), cycles=1.0, **kw):
assert ((warmup * cycles) < 1.0)
warmup = ((warmup * cycles) if (warmup >= 0) else warmup)
super(WarmupCosineWithWarmupRestartsSchedule, self... |
class ColorJitter(object):
def __init__(self, brightness=0, contrast=0, saturation=0, hue=0):
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.hue = hue
def get_params(brightness, contrast, saturation, hue):
transforms = []
i... |
class LogitsProcessorList(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class MABlock(nn.Module):
def __init__(self, conv, kernel_size=3, bias=True, act=nn.ReLU(True)):
super(MABlock, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.k1 = Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=1)
m = []
m.append(conv(1, 1, ker... |
def prepare_validation_features(examples):
examples[question_column_name] = [q.lstrip() for q in examples[question_column_name]]
tokenized_examples = tokenizer(examples[(question_column_name if pad_on_right else context_column_name)], examples[(context_column_name if pad_on_right else question_column_name)], tr... |
def merge_semantic_and_instance(sem_seg, ins_seg, semantic_thing_seg, label_divisor, thing_ids, stuff_area, void_label):
pan_seg = (torch.zeros_like(sem_seg) + void_label)
is_thing = ((ins_seg > 0) & (semantic_thing_seg > 0))
class_id_tracker = Counter()
instance_ids = torch.unique(ins_seg)
for ins_... |
def check_linear_binning(delta):
diff_lambda = np.diff((10 ** delta.log_lambda))
diff_log_lambda = np.diff(delta.log_lambda)
(q5_lambda, q25_lambda) = np.percentile(diff_lambda, [5, 25])
(q5_log_lambda, q25_log_lambda) = np.percentile(diff_log_lambda, [5, 25])
if ((q25_lambda - q5_lambda) < 1e-06):
... |
_module()
class PanopticFPN(TwoStagePanopticSegmentor):
'Implementation of `Panoptic feature pyramid\n networks <
def __init__(self, backbone: ConfigType, neck: OptConfigType=None, rpn_head: OptConfigType=None, roi_head: OptConfigType=None, train_cfg: OptConfigType=None, test_cfg: OptConfigType=None, data_pr... |
class Baseline(abc.ABC):
def __init__(self, sec_from_now: float, helper: PredictHelper):
assert ((sec_from_now % 0.5) == 0), f'Parameter sec from now must be divisible by 0.5. Received {sec_from_now}.'
self.helper = helper
self.sec_from_now = sec_from_now
self.sampled_at = 2
def ... |
def _create_socket_server(path):
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
path_dir = os.path.dirname(path)
os.makedirs(path_dir, exist_ok=True)
if os.path.exists(path):
os.unlink(path)
server.bind(path)
server.listen(0)
return server |
def register(image: ValidImage, /, template: typing.Optional[ValidImage]=None, *, type_of_transform: str='Affine', interpolator: str='bSpline', metric: str='mattes', initial_rigid: bool=True, template_mask: typing.Optional[ValidImage]=None) -> (nib.nifti1.Nifti1Image | ants.ANTsImage):
if (template is None):
... |
class TraceMalloc(threading.Thread):
def __init__(self) -> None:
super().__init__(name=self.__class__.__name__)
def run(self):
process = psutil.Process()
tracemalloc.start(_NUM_FRAMES)
log.info(f'Started tracing memory allocations for {_NUM_FRAMES} frames.')
snapshot = tr... |
_torchsde
class DPMSolverSDESchedulerTest(SchedulerCommonTest):
scheduler_classes = (DPMSolverSDEScheduler,)
num_inference_steps = 10
def get_scheduler_config(self, **kwargs):
config = {'num_train_timesteps': 1100, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'noise_sampler_see... |
class Discriminator(nn.Module):
def __init__(self):
super().__init__()
self.embedding = nn.Embedding(10, 10)
self.layer1 = nn.Sequential(nn.Linear(in_features=((28 * 28) + 10), out_features=1024), nn.LeakyReLU())
self.layer2 = nn.Sequential(nn.Linear(in_features=1024, out_features=51... |
def gen_vqa_texts(annotation):
questions = json.load(open(annotation))['questions']
for q in questions:
(yield q['question']) |
_cache()
def statcast_pitcher_pitch_movement(year: int, minP: Union[(int, str)]='q', pitch_type: str='FF') -> pd.DataFrame:
pitch_type = norm_pitch_code(pitch_type)
url = f'
res = requests.get(url, timeout=None).content
data = pd.read_csv(io.StringIO(res.decode('utf-8')))
data = sanitize_statcast_co... |
def resnet_l123():
model = resnet101(pretrained=True)
del model.layer4
del model.avgpool
del model.fc
return model |
class MultiHeadDotProductAttention(nn.Module):
def __init__(self, d_q_in: int, d_k_in: int, d_v_in: int, d_qk: int, d_v: int, num_heads: int, d_out: int, normalize: bool=True, dropout_p: float=0.0) -> None:
super().__init__()
self.num_heads = num_heads
self.normalize = normalize
self... |
class Joiner(nn.Sequential):
def __init__(self, backbone, position_embedding):
super().__init__(backbone, position_embedding)
def forward(self, tensor_list: NestedTensor):
xs = self[0](tensor_list)
out: List[NestedTensor] = []
pos = []
for (name, x) in xs.items():
... |
class Decoder(layers.Layer):
def __init__(self, *, ch, out_ch, ch_mult=(1, 2, 4, 8), num_res_blocks, attn_resolutions, in_channels, image_size, z_channels, give_pre_end=False, name=None, **ignorekwargs):
super().__init__(name=name)
self.ch = ch
self.num_resolutions = len(ch_mult)
sel... |
def vis_predictions(model, inputs, targets, instructions, save_path, prefix=''):
input_vars = (Variable(tensor.contiguous()) for tensor in inputs)
predictions = model(input_vars)
predictions = predictions.data.cpu().numpy()
targets = targets.cpu().numpy()
num_inputs = inputs[0].size(0)
for ind i... |
def _get_base_voxel_dataset(model_id, edge_length_threshold=0.1, voxel_config=None, filled=False, auto_save=True):
kwargs = dict(model_id=model_id, edge_length_threshold=edge_length_threshold, voxel_config=voxel_config, filled=filled)
subdir = get_voxel_subdir(**kwargs)
if auto_save:
create_voxel_da... |
def load_dataset(args=None, dataset=None):
if (args is not None):
dataset_name = args.dataset.lower()
else:
dataset_name = dataset.lower()
if (dataset_name == 'synthetic_graph_cls'):
return load_synthetic_graph_cls(args)
elif (dataset_name == 'zinc'):
zinc_data = Molecule... |
def resume_model(base_model, args, logger=None):
ckpt_path = os.path.join(args.experiment_path, 'ckpt-last.pth')
if (not os.path.exists(ckpt_path)):
print_log(f'[RESUME INFO] no checkpoint file from path {ckpt_path}...', logger=logger)
return (0, 0)
print_log(f'[RESUME INFO] Loading model we... |
def main(output_dir, palette=sns.color_palette('light:#5A9', as_cmap=True), annot=False, output_dpi=600, linewidth=2.0, context='paper', fig_scale=1.5):
sns.set_context(context, font_scale=3.0)
common_kwargs = dict(cmap=palette, annot=annot, annot_kws={'fontsize': 18}, fmt='.1f', cbar=True, xticklabels=True, yt... |
def convert_all_files(dataset='uea'):
assert (dataset in ['uea', 'ucr'])
if (dataset == 'uea'):
folder = 'UEA'
elif (dataset == 'ucr'):
folder = 'UCR'
arff_folder = (DATA_DIR + '/raw/{}/Multivariate_arff'.format(folder))
for ds_name in tqdm([x for x in os.listdir(arff_folder) if os.p... |
def get_format_custom(logger, level):
if ('RANK' in os.environ):
rank = int(os.environ['RANK'])
if (level == logging.INFO):
logger.addFilter(Filter((rank == 0)))
else:
rank = 0
format_str = '[%(asctime)s-rk{}-%(message)s'.format(rank)
formatter = logging.Formatter(for... |
def chunked(n: int, data: Iterable[T]) -> Iterator[list[T]]:
data_iter = iter(data)
def take(n: int, data_iter: Iterator[T]) -> Iterable[T]:
for _ in range(n):
try:
(yield next(data_iter))
except StopIteration:
return
while (len((result := list... |
def quaternionProduct(qx, qy):
a = qx[0]
b = qx[1]
c = qx[2]
d = qx[3]
e = qy[0]
f = qy[1]
g = qy[2]
h = qy[3]
q1 = ((((a * e) - (b * f)) - (c * g)) - (d * h))
q2 = ((((a * f) + (b * e)) + (c * h)) - (d * g))
q3 = ((((a * g) - (b * h)) + (c * e)) + (d * f))
q4 = ((((a * h... |
def main():
g = Github(os.environ['GITHUB_TOKEN'])
repo = g.get_repo('huggingface/transformers')
open_issues = repo.get_issues(state='open')
for issue in open_issues:
comments = sorted([comment for comment in issue.get_comments()], key=(lambda i: i.created_at), reverse=True)
last_comment... |
class Deconv2DNoBiasLayerGuidedBackProp(Deconv2DNoBiasLayer):
def output(self, input=None, dropout_active=True, *args, **kwargs):
if (input is None):
input = self.input_layer.output(*args, dropout_active=dropout_active, **kwargs)
if (dropout_active and (self.dropout > 0.0)):
... |
def ismember(a_vec, b_vec):
bool_ind = np.isin(a_vec, b_vec)
common = a_vec[bool_ind]
(common_unique, common_inv) = np.unique(common, return_inverse=True)
(b_unique, b_ind) = np.unique(b_vec, return_index=True)
return bool_ind |
def rescale_attributions_to_tokens(attributions: OneOrMoreAttributionSequences, tokens: OneOrMoreTokenSequences) -> OneOrMoreAttributionSequences:
return [(attr[:len(tokens)] if (not all((math.isnan(x) for x in attr))) else []) for (attr, tokens) in zip(attributions, tokens)] |
class TFElectraPreTrainedModel(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class PolyConvSeqBranch(nn.Module):
def __init__(self, in_channels, out_channels_list, kernel_size_list, strides_list, padding_list, num_blocks):
super(PolyConvSeqBranch, self).__init__()
assert (len(out_channels_list) == len(kernel_size_list))
assert (len(out_channels_list) == len(strides_l... |
class FP16_Optimizer(object):
def __init__(self, optimizer, static_loss_scale=1.0, dynamic_loss_scale=False):
if (not torch.cuda.is_available):
raise SystemError('Cannot use fp16 without CUDA')
self.fp16_param_groups = []
self.fp32_param_groups = []
self.fp32_flattened_gr... |
def apply_delta_low_cpu_mem(base_model_path, target_model_path, delta_path):
base_tokenizer = AutoTokenizer.from_pretrained(base_model_path, use_fast=False)
base_config = AutoConfig.from_pretrained(base_model_path)
if os.path.exists(target_model_path):
shutil.rmtree(target_model_path)
target_mod... |
class RemBertTokenizer(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, do_lower_case=False, remove_space=True, keep_accents=True, bos_token='[... |
def assert_params_all_zeros(module) -> bool:
weight_data = module.weight.data
is_weight_zero = weight_data.allclose(weight_data.new_zeros(weight_data.size()))
if (hasattr(module, 'bias') and (module.bias is not None)):
bias_data = module.bias.data
is_bias_zero = bias_data.allclose(bias_data.... |
def main():
parser = argparse.ArgumentParser(description='Convert model keys')
parser.add_argument('src', help='src detectron model path')
parser.add_argument('dst', help='save path')
args = parser.parse_args()
convert(args.src, args.dst) |
class TestMetrics(unittest.TestCase):
def test_tensorflow_2(self):
image = np.ones([256, 256, 1])
resize_kwargs = {'size': [224, 224]}
transforms = TRANSFORMS(framework='tensorflow', process='preprocess')
resize = transforms['Resize'](**resize_kwargs)
random_crop_kwargs = {'s... |
def virno():
colors1 = pl.cm.viridis(np.linspace(0.0, 1, 128))
colors2 = pl.cm.inferno_r(np.linspace(0.0, 1, 128))
colors = np.vstack((colors1[5:][::(- 1)], colors2[12:99][::(- 1)]))
virno = mcolors.LinearSegmentedColormap.from_list('virno', colors)
return virno |
def set_logger(ckpt_dir, seed, log_dir=None):
logger = logging.getLogger(str(seed))
logger.propagate = False
for handler in logger.handlers[:]:
logger.removeHandler(handler)
ch = logging.StreamHandler()
ch.setFormatter(LoggingFormatter())
logger.addHandler(ch)
if (log_dir is None):
... |
def learn(env, policy_fn, *, timesteps_per_actorbatch, clip_param, entcoeff, optim_epochs, optim_stepsize, optim_batchsize, gamma, lam, max_timesteps=0, max_episodes=0, max_iters=0, max_seconds=0, callback=None, adam_epsilon=1e-05, schedule='constant'):
ob_space = env.observation_space
ac_space = env.action_spa... |
def one_hot_from_int(int_or_list, batch_size=1):
if isinstance(int_or_list, int):
int_or_list = [int_or_list]
if ((len(int_or_list) == 1) and (batch_size > 1)):
int_or_list = ([int_or_list[0]] * batch_size)
assert (batch_size == len(int_or_list))
array = np.zeros((batch_size, NUM_CLASSES... |
def get_enum_name_by_value():
desc = caffe_pb2.LayerParameter.LayerType.DESCRIPTOR
d = {}
for (k, v) in desc.values_by_name.items():
d[v.number] = k
return d |
def _build_q_model_and_distribution(policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict) -> Tuple[(ModelV2, TorchDistributionWrapper)]:
return (_build_q_models(policy, obs_space, action_space, config), TorchCategorical) |
def _test_from_save_pretrained_dynamo(in_queue, out_queue, timeout):
error = None
try:
(init_dict, model_class) = in_queue.get(timeout=timeout)
model = model_class(**init_dict)
model.to(torch_device)
model = torch.compile(model)
with tempfile.TemporaryDirectory() as tmpdi... |
class UIScreenClassifier(pl.LightningModule):
def __init__(self, num_classes=20, dropout_block=0.0, dropout=0.2, lr=5e-05, soft_labels=True, stochastic_depth_p=0.2, arch='resnet50'):
super(UIScreenClassifier, self).__init__()
self.save_hyperparameters()
if ((arch == 'resnet50') or (arch == '... |
class LambdaMap(LambdaBase):
def forward(self, input):
return list(map(self.lambda_func, self.forward_prepare(input))) |
def load_sub_model(library_name: str, class_name: str, importable_classes: List[Any], pipelines: Any, is_pipeline_module: bool, pipeline_class: Any, torch_dtype: torch.dtype, provider: Any, sess_options: Any, device_map: Optional[Union[(Dict[(str, torch.device)], str)]], max_memory: Optional[Dict[(Union[(int, str)], Un... |
()
('--load_model', default=False)
('--data_path', default='./data/diabetes-vfl-1.csv')
def run_client(load_model, data_path):
init_fl_context(1)
df_train = pd.read_csv(data_path)
df_train['ID'] = df_train['ID'].astype(str)
psi = PSI()
intersection = psi.get_intersection(list(df_train['ID']))
df... |
def test_generate_motion_primitives():
vp = VehicleParameters.default_car()
vg = VehicleGeometry.default_car()
params = MPGParam(dt=Decimal('.2'), n_steps=3, velocity=(0, 50, 3), steering=((- vp.delta_max), vp.delta_max, 3))
vehicle = BicycleDynamics(vg=vg, vp=vp)
mpg = MotionPrimitivesGenerator(par... |
class Extra(Component):
def __init__(self, display_data=None, output_names=None, output_indexes=None, main_effects=None, hierarchical_values=None, clustering=None):
self.fields = locals()
del self.fields['self'] |
class LookupTable(Layer):
def __init__(self, n_index, n_output, padding_value=0.0, max_norm=DOUBLEMAX, norm_type=2.0, should_scale_grad_by_freq=False, wRegularizer=None, bigdl_type='float'):
super(LookupTable, self).__init__(None, bigdl_type, n_index, n_output, padding_value, max_norm, norm_type, should_sca... |
def union(x, y, parents, sizes):
x_root = find(x, parents)
y_root = find(y, parents)
if (x_root == y_root):
return
if (sizes[x_root] > sizes[y_root]):
parents[y_root] = x_root
sizes[x_root] += sizes[y_root]
else:
parents[x_root] = y_root
sizes[y_root] += sizes... |
class FSMTTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, langs=None, src_voca... |
class baseline(nn.Module):
def __init__(self, backbone, c=64):
super(baseline, self).__init__()
self.name = backbone
self.encoder = Encoder(backbone, c)
self.decoder = baseU(backbone, c)
def forward(self, X, phase='te'):
encoders = self.encoder(X)
OutDict = self.d... |
class PDF(DocumentParser):
def __init__(self, path, output='txt'):
self.content = self._parse(path, format=output)
def _parse(self, path, *args, **kwargs):
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.con... |
def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict:
train_dataset = SupervisedDataset(tokenizer=tokenizer, data_path=data_args.data_path)
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
return dict(train_dataset=train_dataset, eval_dataset=N... |
class RRDB(nn.Module):
def __init__(self, num_feat, num_grow_ch=32):
super(RRDB, self).__init__()
self.rdb1 = ResidualDenseBlock(num_feat, num_grow_ch)
self.rdb2 = ResidualDenseBlock(num_feat, num_grow_ch)
self.rdb3 = ResidualDenseBlock(num_feat, num_grow_ch)
def forward(self, x)... |
def subset2dataset(subset):
dataset = subset
while isinstance(dataset, Subset):
dataset = dataset.dataset
return dataset |
def prologue_init(args, input_args, args_dict):
output = dict()
subset_target = 'train'
(placement_scr, parent, exp_name) = (None, None, None)
placement_node = None
eval = (not (args.fd_exp in [None, '']))
tag = [('id', args.exp_id), ('tsk', args.task), ('ds', args.dataset), ('sd', args.MYSEED),... |
class ConvLayer(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, IN=False):
super(ConvLayer, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, bias=False, groups=groups)
if IN:
... |
def remove_dup_initializers(onnx_file_path):
model_file_folder = os.path.dirname(onnx_file_path)
model_file_name = os.path.basename(onnx_file_path)
model = onnx.load(os.path.join(model_file_folder, model_file_name))
inits = list(model.graph.initializer)
dup_set = set()
dup_map = {}
ind_to_re... |
def parse_cmd_options(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--no_reslink', action='store_true')
parser.add_argument('--dropout_rate', type=float, default=None)
(module_opt, _) = parser.parse_known_args(argv)
return module_opt |
class CorNet(nn.Module):
def __init__(self, output_size, cornet_dim=1000, n_cornet_blocks=2, **kwargs):
super(CorNet, self).__init__()
self.intlv_layers = nn.ModuleList([CorNetBlock(cornet_dim, output_size, **kwargs) for _ in range(n_cornet_blocks)])
for layer in self.intlv_layers:
... |
class TrainerCVRP(TrainerBase):
def get_reward_name() -> str:
return 'tour_length'
def is_reward_positive() -> bool:
return False
def get_observation_type() -> Type[Observation]:
return Observation
def init_encoder(self, num_layers, name) -> EncoderBase:
return CVRPEncode... |
def one_d_convert(indices, cutoffs, shape_list):
one_d_indices = {}
for item in indices:
layer_num = np.where((item > cutoffs))[0]
curr_layer_index = (item - cutoffs[layer_num])
one_d_indices[str(layer_num)] = curr_layer_index
return one_d_indices |
class edic(dict):
def __and__(self, other):
return edic({k: other[k] for k in (set(self) & set(other))})
def __rand__(self, other):
return edic({k: self[k] for k in (set(other) & set(self))})
def __or__(self, other):
return edic({**self, **other})
def __ror__(self, other):
... |
class AvgMeter(object):
name = 'No name'
def __init__(self, name='No name'):
self.name = name
self.reset()
def reset(self):
self.sum = 0
self.mean = 0
self.num = 0
self.now = 0
def update(self, mean_var, count=1):
if math.isnan(mean_var):
... |
_registry(algorithm_type='weight_correction', location='post_quantization')
class WeightCorrection(Algorithm):
def __init__(self, eps=1e-05, channel_axis=1):
self.eps = eps
self.channel_axis = channel_axis
def __call__(self, origin_model, q_model, adaptor, dataloader, iterations):
graph_... |
class FC(tf.keras.Sequential):
def __init__(self, in_size: int, out_size: int, *, activation=tf.keras.layers.ReLU(), bn: bool=False, init=None, preact: bool=False, training=True):
super().__init__()
fc = tf.keras.layers.Linear(in_size, out_size, use_bias=(not bn), kernel_initializer=init, bias_initi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.