code stringlengths 101 5.91M |
|---|
class StableDiffusionInpaintPipelineLegacy(metaclass=DummyObject):
_backends = ['torch', 'transformers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch', 'transformers'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['torch', 'transformers'])
def fr... |
def load_data_table(table, image_dir, corrupt_images=None):
print('Loading dataframe for', table)
df = pd.read_csv(table)
print('Found', len(df), 'images in table')
df['filepath'] = df.apply((lambda row: get_image_filepath(row, image_dir)), axis=1)
len_before = len(df)
if (corrupt_images is not ... |
class TrialOutput(object):
def __init__(self, config, model_path):
self.config = config
self.model_path = model_path |
class Entity(object):
def __init__(self):
self.name = ''
self.size = 0.05
self.movable = False
self.collide = True
self.density = 25.0
self.color = None
self.max_speed = None
self.accel = None
self.max_a_speed = None
self.state = Entity... |
class ConvolutionalAutoencoder(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv1 = torch.nn.Conv2d(3, 32, 3, padding=1)
self.conv2 = torch.nn.Conv2d(32, 64, 3, padding=1)
self.conv3 = torch.nn.Conv2d(64, 128, 3, padding=1)
self.conv4 = torch.nn.Conv2d(128, l... |
class CiteseerBiGraph(BaseData):
def __init__(self, data_root: Optional[str]=None) -> None:
super().__init__('citeseer_bigraph', data_root)
self._content = {'num_u_classes': 6, 'num_u_vertices': 1237, 'num_v_vertices': 742, 'num_edges': 1665, 'dim_u_features': 3703, 'dim_v_features': 3703, 'u_featur... |
def make_chem_data(rule, train=True):
is_train = ('train' if train else 'test')
x_data = np.load(osp.join(foldername, (((('logic_' + str(rule)) + '_X_') + is_train) + '.npy')))
y_data = np.load(osp.join(foldername, (((('logic_' + str(rule)) + '_Y_') + is_train) + '.npy')))
return (x_data, y_data) |
def test_pvt():
with pytest.raises(TypeError):
PyramidVisionTransformer(pretrained=123)
with pytest.raises(AssertionError):
PyramidVisionTransformer(pretrain_img_size=(224, 224, 224))
temp = torch.randn((1, 3, 224, 224))
model = PyramidVisionTransformer(pretrain_img_size=224, use_abs_pos... |
def seresnet200b(**kwargs):
return get_seresnet(blocks=200, conv1_stride=False, model_name='seresnet200b', **kwargs) |
.parametrize('model_name, with_cls_token, share_embeddings, return_dataframe', [('saint', False, True, False), ('saint', True, True, False), ('saint', False, False, False), ('saint', False, True, True), ('saint', True, True, True), ('saint', False, False, True), ('fttransformer', False, True, False), ('fttransformer', ... |
class TFAlbertModelTester():
def __init__(self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, embedding_size=16, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37, hidden_act='gelu', hidden_dropout_... |
def _pcfg(url='', hf_hub='', mean=None, std=None):
return dict(url=url, hf_hub=hf_hub, mean=mean, std=std) |
def autoselect(method: str, source: Optional[str]=None, backend: Optional[str]=None, **kwargs) -> StainNormalizer:
if (backend is None):
backend = sf.backend()
if (backend == 'tensorflow'):
import slideflow.norm.tensorflow
BackendNormalizer = sf.norm.tensorflow.TensorflowStainNormalizer
... |
def get_hashes_and_lines(raw_line):
hash = hashlib.md5(raw_line).hexdigest()
return (hash, raw_line) |
def plot_precision_recall(data, ax=None):
df = pandas.DataFrame({'threshold': numpy.linspace(0, 1.0, 50, endpoint=False)})
micro = df.apply((lambda r: score(data, average='micro', threshold=r.threshold)), axis=1)
micro['threshold'] = df.threshold
micro['micro'] = micro.precision
macro = df.apply((la... |
def hawq_top(fp32_model, q_model, dataloader, criterion, enable_act):
orig_eval = True
if fp32_model.training:
orig_eval = False
fp32_model.eval()
ht = HessianTrace(fp32_model, dataloader=dataloader, q_model=q_model)
traces = ht.get_avg_traces(enable_act, num_sample=0)
op_to_traces = tra... |
def get_random_walk_eval(sos_key, nodes, edges, nsample=5):
group = []
cnt = 0
while (cnt <= nsample):
rand_1 = random_walk_from_sos(sos_key, nodes, edges)
sample_sent1 = tokenizer.decode(rand_1, skip_special_tokens=True)
group.append(sample_sent1)
cnt += 1
stat = {}
... |
def _conv_flops_compute(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1):
assert ((weight.shape[1] * groups) == input.shape[1])
batch_size = input.shape[0]
in_channels = input.shape[1]
out_channels = weight.shape[0]
kernel_dims = list(weight.shape[2:])
input_dims = list(input... |
class AdversarialEpocher(SemiSupervisedEpocher, ABC):
def _assertion(self):
pass
def __init__(self, *, model: nn.Module, optimizer: T_optim, labeled_loader: T_loader, unlabeled_loader: T_loader, sup_criterion: T_loss, num_batches: int, cur_epoch=0, device='cpu', two_stage: bool=False, disable_bn: bool=F... |
class TestCommutationAnalysis(QiskitTestCase):
def setUp(self):
self.pass_ = CommutationAnalysis()
self.pset = self.pass_.property_set = PropertySet()
def assertCommutationSet(self, result, expected):
result_to_compare = {}
for (qbit_str, sets) in result.items():
if (... |
class RandomColorDistortion():
def __init__(self, s: float=1.0):
self.color_distort = compose_color_distortion(s=s)
def __call__(self, x):
return self.color_distort(x) |
def train(cfg, local_rank, distributed, tblogger=None, transfer_weight=False, adjust_lr=False, skip_val=False, no_head=False):
model = build_detection_model(cfg)
device = torch.device('cuda')
model.to(device)
optimizer = make_optimizer(cfg, model)
scheduler = make_lr_scheduler(cfg, optimizer)
if... |
class Discriminator(nn.Module):
def __init__(self, preprocess_GAN_mode, input_channel, batch_size=64, image_size=64, conv_dim=64):
super(Discriminator, self).__init__()
self.imsize = image_size
layer1 = []
layer2 = []
layer3 = []
last = []
layer1.append(Spectr... |
def custom_figure(n_panels=2, width=8.0, panel_aspect_ratio=1.0, extra_top_space=False, reduce_vertical_sep=False):
if isinstance(n_panels, collections.Sequence):
(n_panels_h, n_panels_v) = n_panels
else:
n_panels_h = n_panels
n_panels_v = 1
_margin_t_absolute = (margin_t_absolute_ex... |
def get_fbank(path_or_fp: Union[(str, BinaryIO)], n_bins=80) -> np.ndarray:
(sound, sample_rate) = get_waveform(path_or_fp, normalization=False)
features = _get_kaldi_fbank(sound, sample_rate, n_bins)
if (features is None):
features = _get_torchaudio_fbank(sound, sample_rate, n_bins)
if (feature... |
def load_classifier(name='resnet101', n=2):
model = torchvision.models.__dict__[name](pretrained=True)
filters = model.fc.weight.shape[1]
model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
model.fc.out_features... |
def initialize_hyperparameters(PATHS: dict, load_target: str, config_name: str='default', n_envs: int=1) -> dict:
if (load_target is None):
hyperparams = load_hyperparameters_json(PATHS=PATHS, from_scratch=True, config_name=config_name)
hyperparams['agent_name'] = PATHS['model'].split('/')[(- 1)]
... |
def timed_run(f: FunctionType, timeout_seconds: int=3600) -> Tuple[(Any, Number, bool)]:
start_time = time.time()
with Timeout(timeout_seconds) as timeout_ctx:
res = f()
duration = (time.time() - start_time)
timed_out = (timeout_ctx.state == timeout_ctx.TIMED_OUT)
if timed_out:
res =... |
_arguments_as_properties('lost_lang', 'known_lang', 'capacity', 'num_cognates')
class Evaluator():
def __init__(self, model, data_loader):
self.model = model
self.data_loader = data_loader
self._settings = list()
def add_setting(self, mode=None, edit=None):
assert (mode in ['mle'... |
def _handle_path(path, sess, low_profile=False):
if isinstance(path, str):
f = np.load(path)
(m, s) = (f['mu'][:], f['sigma'][:])
f.close()
else:
files = path
if low_profile:
(m, s) = calculate_activation_statistics_from_files(files, sess)
else:
... |
def num_dependent_clauses(const_pt):
dep_clauses = []
clause_tags = None
if (settings.LANGUAGE in ['zh-hant', 'fr']):
lang = settings.LANGUAGE
else:
lang = 'default'
clause_tags = SUBORD_CLAUSE_LANGUAGE_MAP[lang]
for clause_tag in clause_tags:
for leaf in _leaves(const_pt... |
class ConfigTester(unittest.TestCase):
def test_outputs_single_attribute(self):
outputs = CustomOutput(images=np.random.rand(1, 3, 4, 4))
assert isinstance(outputs.images, np.ndarray)
assert (outputs.images.shape == (1, 3, 4, 4))
assert isinstance(outputs['images'], np.ndarray)
... |
def update_config(config, data_sets):
config.max_num_sents = 0
config.max_sent_size = 0
config.max_ques_size = 0
config.max_ques_sub_size = 0
config.max_word_size = 0
config.max_para_size = 0
for data_set in data_sets:
data = data_set.data
shared = data_set.shared
for... |
def render_batch(visualize_fn, input, target, output):
batch_size = input.shape[0]
(fig, axes) = plt.subplots(nrows=batch_size, ncols=3, figsize=(12, (4 * batch_size)))
plt.subplots_adjust(left=0.05, bottom=0, right=0.95, top=1, hspace=0)
for i in range(batch_size):
ax = (axes if (batch_size == ... |
def create_model(arch, heads, head_conv):
num_layers = (int(arch[(arch.find('_') + 1):]) if ('_' in arch) else 0)
arch = (arch[:arch.find('_')] if ('_' in arch) else arch)
get_model = _model_factory[arch]
model = get_model(num_layers=num_layers, heads=heads, head_conv=head_conv)
return model |
def labels2clusters(labels):
lb2idxs = {}
for (idx, lb) in enumerate(labels):
if (lb not in lb2idxs):
lb2idxs[lb] = []
lb2idxs[lb].append(idx)
clusters = [idxs for (_, idxs) in lb2idxs.items()]
return clusters |
_tf
class TFCTRLModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = ((TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ())
all_generative_model_classes = ((TFCTRLLMHeadModel,) if is_tf_available() else ())
pipeline_model_mappin... |
def summarize_evaluation(evaluation: pd.DataFrame) -> dict:
if ((evaluation is None) or (len(evaluation) == 0)):
warnings.warn('No completions to evaluate.')
return None
return {'accuracy': evaluation.correct.mean(), 'contains_answer': evaluation.contains_answer.mean(), 'correct_format': evaluat... |
class HistoricalContainer(metaclass=ABCMeta):
def __init__(self) -> None:
self._record_dict: _Save_Type = OrderedDict()
self._current_epoch: int = 0
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def trainer(self):
return self... |
def write_podspec(f, rules, args):
rule_dir = build_rule_directory(rules)['abseil']
spec = re.sub('\\$\\{(\\w+)\\}', (lambda x: args[x.group(1)]), SPEC_TEMPLATE).lstrip()
f.write(spec)
write_podspec_map(f, rule_dir, 0)
f.write('end\n') |
def add_ground_truth_to_proposals_single_image(gt_boxes, proposals):
device = proposals.objectness_logits.device
gt_logit_value = math.log(((1.0 - 1e-10) / (1 - (1.0 - 1e-10))))
gt_logits = (gt_logit_value * torch.ones(len(gt_boxes), device=device))
gt_proposal = Instances(proposals.image_size)
gt_p... |
class Up(nn.Module):
def __init__(self, in_channels, out_channels, bilinear=True):
super().__init__()
if bilinear:
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
self.conv = DoubleConv(in_channels, out_channels, (in_channels // 2))
else:
... |
class TestTorchOP(unittest.TestCase):
def setUpClass(self):
pass
def tearDownClass(self):
pass
def test_1(self):
n = Net('div')
example_in = torch.rand(3, 256)
example_in2 = torch.rand(256)
traced_model = torch.jit.trace(n, (example_in, example_in2))
t... |
def score_amr_pairs(f1, f2, justinstance=False, justattribute=False, justrelation=False):
total_match_num = total_test_num = total_gold_num = 0
for (sent_num, (cur_amr1, cur_amr2)) in enumerate(generate_amr_lines(f1, f2), start=1):
(best_match_num, test_triple_num, gold_triple_num) = get_amr_match(cur_a... |
class YGate(Gate):
def __init__(self, label=None):
super().__init__('y', 1, [], label=label)
def _define(self):
definition = []
q = QuantumRegister(1, 'q')
rule = [(U3Gate(pi, (pi / 2), (pi / 2)), [q[0]], [])]
for inst in rule:
definition.append(inst)
... |
def get_target_feature(model, preprocess, tokenizer_funct, device, target_images=None, target_prompts=None):
if (target_images is not None):
with torch.no_grad():
curr_images = [preprocess(i).unsqueeze(0) for i in target_images]
curr_images = torch.concatenate(curr_images).to(device)... |
def main():
with codecs.open('results.csv', 'w', 'utf-8') as fp:
writer = csv.writer(fp)
writer.writerow(['experiment', 'model', 'error', 'elapsed'])
start_time = time.time()
run_experiment(writer, 'counts', generate_data_counts)
run_experiment(writer, 'quad', generate_data_q... |
class FangraphsBattingStats(FangraphsStatsBase):
COMMON = 'c'
LINE_BREAK = '-1'
NAME = '0'
TEAM = '1'
SEASON = '2'
AGE = '3'
G = '4'
GAMES = G
AB = '5'
AT_BATS = AB
PA = '6'
PLATE_APPEARANCES = PA
H = '7'
HITS = H
SINGLES = '8'
DOUBLES = '9'
TRIPLES = ... |
class Normalize(object):
def __init__(self, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), inplace=False):
self.mean = mean
self.std = std
self.inplace = inplace
def __call__(self, x):
if (isinstance(x, torch.Tensor) and (len(x.shape) == 3)):
x = F.normalize(x, self.mean,... |
class DepthWise(Module):
def __init__(self, in_c, out_c, residual=False, kernel=(3, 3), stride=(2, 2), padding=(1, 1), groups=1):
super(DepthWise, self).__init__()
self.residual = residual
self.layers = nn.Sequential(ConvBlock(in_c, out_c=groups, kernel=(1, 1), padding=(0, 0), stride=(1, 1))... |
class ModelTest(unittest.TestCase):
def check_parameter_count(self, model, target_in_m):
count = (model.count_params() / (10 ** 6))
msg = '{} params #{}M suppose to be #{}M.'.format(model.name, count, target_in_m)
self.assertAlmostEqual(target_in_m, count, msg=msg, delta=0.1)
def check_p... |
class ConfigManger():
DEFAULT_CONFIG = ''
def __init__(self, DEFAULT_CONFIG_PATH: str=None, verbose=True, integrality_check=True) -> None:
self.parsed_args: Dict[(str, Any)] = YAMLArgParser(verbose=verbose)
if (DEFAULT_CONFIG_PATH is None):
warnings.warn('No default yaml is provided,... |
class BLS2017Model(nn.Module):
def __init__(self, num_filters=192):
super(BLS2017Model, self).__init__()
self.conv1 = nn.Conv2d(3, num_filters, 9, stride=4, padding=4)
self.gdn1 = gdn.GDN(num_filters)
self.conv2 = nn.Conv2d(num_filters, num_filters, 5, stride=2, padding=2)
se... |
def where(condition, input, other):
if is_encrypted_tensor(condition):
return ((condition * input) + ((1 - condition) * other))
elif torch.is_tensor(condition):
condition = condition.float()
return ((input * condition) + (other * (1 - condition))) |
def mIoU_parser():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--dataset', type=str, default=(basedir + '/Dataset'), help='path to dataset')
parser.add_argument('--set_name', type=str, default='val.txt', help='name for set')
parser.add_ar... |
class Merge_Run(nn.Module):
def __init__(self, in_channels, out_channels, init='xavier', ksize=3, stride=1, pad=1, dilation=1):
super(Merge_Run, self).__init__()
self.body1 = nn.Sequential(nn.Conv2d(in_channels, out_channels, ksize, stride, pad), nn.LeakyReLU(negative_slope=0.2, inplace=True))
... |
.parametrize('emitter_type', ['GradientArborescenceEmitter', 'EvolutionStrategyEmitter'], ids=['GAEmitter', 'ESEmitter'])
.parametrize('wrong_array,offsets', [('solution_batch', [(0, 1), (1, 0)]), ('objective_batch', [(1,)]), ('measures_batch', [(0, 1), (1, 0)]), ('jacobian_batch', [(0, 0, 1), (0, 1, 0), (1, 0, 0)]), (... |
def attention(x):
params = dict(activation='relu', padding='valid', kernel_regularizer=l2(1e-05))
x = Conv2D(8, kernel_size=3, **params)(x)
x = Conv2D(16, kernel_size=3, **params)(x)
x = Conv2D(32, kernel_size=3, **params)(x)
x = Conv2D(1, kernel_size=3)(x)
x = MaxPooling2D(pool_size=8)(x)
x... |
def define_net_r(opt):
network_type = opt.pop('type')
net_r = dynamic_instantiation(_arch_modules, network_type, opt)
return net_r |
def get_charset(lang):
global _CHARSETS
cls_or_obj = _CHARSETS[lang]
if isinstance(cls_or_obj, type):
_CHARSETS[lang] = cls_or_obj()
return _CHARSETS[lang] |
class GeneralDataset(Dataset):
def __init__(self, root, transform=None, target_transform=None, top_k=(1, 5), keep_rgb=False):
self.data_set = datasets.ImageFolder(root)
self.classes = self.data_set.classes
self.root = root
self.transform = transform
self.target_transform = ta... |
def get_and_print_layers_to_use_halut(model: torch.nn.Module) -> list[str]:
all_layers = []
def layers(module: torch.nn.Module, prefix: str='') -> None:
if isinstance(module, (HalutLinear, HalutConv2d)):
all_layers.append(prefix[:(- 1)])
for (name, child) in module._modules.items():
... |
def test_shape_validation_during_creation():
tensor = torch.tensor(np.random.rand(3))
with pytest.raises(ValueError):
box_tensor = MinDeltaBoxTensor(tensor)
tensor = torch.tensor(np.random.rand(3, 11))
with pytest.raises(ValueError):
box_tensor = MinDeltaBoxTensor(tensor)
tensor = to... |
def get_d_UB(l, u, func, dfunc):
diff = (lambda d, l: (((func(d) - func(l)) / (d - l)) - dfunc(d)))
max_iter = 1000
ub = (- l)
d = (ub / 2)
device = l.device
lb = torch.zeros(l.shape, device=device)
keep_search = torch.ones(l.shape, device=device).byte()
for i in range(max_iter):
... |
class _ClassInfo(_BlockInfo):
def __init__(self, name, class_or_struct, clean_lines, linenum):
_BlockInfo.__init__(self, False)
self.name = name
self.starting_linenum = linenum
self.is_derived = False
if (class_or_struct == 'struct'):
self.access = 'public'
... |
def area(x, y):
ymax = np.max(y)
xmax = np.max(x)
bin_mask = np.zeros((ymax, xmax))
(rr, cc) = polygon(y, x)
bin_mask[(rr, cc)] = 1
area = np.sum(bin_mask)
return area |
class CIFAR100(DATASET):
_target_: str = 'dataset_loaders.load_CIFAR100'
name: str = 'CIFAR100'
IN_CHANNEL: int = 3
N_CLASSES: int = 100
IMG_SIZE: Tuple[int] = field(default_factory=(lambda : (32, 32))) |
def mkdir(directory: str) -> None:
return pathlib.Path(directory).mkdir(parents=True, exist_ok=True) |
class ROSDataManagerConfig(base_datamanager.VanillaDataManagerConfig):
_target: Type = field(default_factory=(lambda : ROSDataManager))
dataparser: ROSDataParserConfig = ROSDataParserConfig()
publish_training_posearray: bool = True
data_update_freq: float = 5.0
num_training_images: int = 500 |
class CheckpointFunction(torch.autograd.Function):
def forward(ctx, run_function, preserve_rng_state, *args):
check_backward_validity(args)
ctx.run_function = run_function
ctx.preserve_rng_state = preserve_rng_state
ctx.fwd_cuda_rng_state_tracker = get_cuda_rng_tracker().get_states()... |
def render_batch(npy_dir, execute_python='./scripts/visualize_motion.sh', mode='sequence'):
os.system(f'{execute_python} {npy_dir} {mode}') |
def test_components_vs_sklearn():
def check_components(Estimator, n_components, shape):
X = DATA[shape]
pca = Estimator(n_components, **KWDS[Estimator]).fit(X)
skpca = SKPCA(n_components).fit(X)
assert_columns_allclose_upto_sign(pca.components_.T, skpca.components_.T)
for Estimat... |
def base_cli_dir_args(image: pathlib.Path, mask: pathlib.Path) -> typing.List[str]:
return f'{image.parent} -m {mask.parent}'.split() |
class DistogramHead(nn.Module):
def __init__(self, c_z, no_bins, **kwargs):
super(DistogramHead, self).__init__()
self.c_z = c_z
self.no_bins = no_bins
self.linear = Linear(self.c_z, self.no_bins, init='final')
def forward(self, z):
logits = self.linear(z)
logits ... |
def _config_validation(config):
if (config == None):
return None
if (isinstance(config, dict) != True):
with open(config, 'r') as conf_file:
import yaml
config = yaml.safe_load(conf_file)
from schema import Schema
conf_schema = Schema({'pattern_switch': Schema({st... |
class ObjectData():
def __init__(self, id, x, y):
self.id = id
self.x = x
self.y = y
self.type = 'other' |
class SUBDATA(data.Dataset):
def __init__(self):
self.data = np.load('./data/sub_data_training.npy', allow_pickle=True)
def __getitem__(self, index):
return (self.data[index][0], self.data[index][1], self.data[index][2], self.data[index][3], self.data[index][4], self.data[index][5], self.data[in... |
def train(args, train_dataset, model, tokenizer, teacher=None):
if (args.local_rank in [(- 1), 0]):
tb_writer = SummaryWriter()
args.train_batch_size = (args.per_gpu_train_batch_size * max(1, args.n_gpu))
train_sampler = (RandomSampler(train_dataset) if (args.local_rank == (- 1)) else DistributedSam... |
def adjust_improvedgt_folders(kitti_folder='kitti_download'):
path_getter = gp.GetPath()
dataset_folder_path = path_getter.get_data_path()
gt_path = os.path.join(dataset_folder_path, kitti_folder)
gt_path = os.path.join(gt_path, 'Depth_improved')
assert os.path.isdir(gt_path), 'Path to data does not... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model', required=True, help='sentencepiece model to use for decoding')
parser.add_argument('--input', required=True, help='input file to decode')
parser.add_argument('--input_format', choices=['piece', 'id'], default='piece')
args... |
class RSSMPosterior(nn.Module):
c: Config
def __call__(self, prior, obs_inputs):
inputs = jnp.concatenate([prior['det_out'], obs_inputs], (- 1))
hl = nn.relu(nn.Dense(self.c.cell_embed_size)(inputs))
hl = nn.relu(nn.Dense(self.c.cell_embed_size)(hl))
mean = nn.Dense(self.c.cell_s... |
def get_llm_packages():
llm_packages = []
for (dirpath, _, _) in os.walk(os.path.join(llm_home, 'bigdl')):
print(dirpath)
package = dirpath.split((llm_home + os.sep))[1].replace(os.sep, '.')
if any((fnmatch.fnmatchcase(package, pat=pattern) for pattern in exclude_patterns)):
... |
def constrain_norm(grads: P, preconditioned_grads: P, learning_rate: chex.Numeric, norm_constraint: chex.Numeric=0.001) -> P:
sq_norm_grads = tree_inner_product(preconditioned_grads, grads)
sq_norm_scaled_grads = (sq_norm_grads * (learning_rate ** 2))
sq_norm_scaled_grads = utils.distribute.pmean_if_pmap(sq... |
.skip(reason='make_bag test needs to be updated')
def test_make_bag_regression():
data = synthetic_regression()
X_orig = data['full']['X']
y_orig = data['full']['y']
X = np.array(X_orig)
y = np.array(y_orig)
w = np.ones_like(y, dtype=np.float64)
test_size = 0.2
(X_train, X_val, y_train, ... |
def get_total(records):
record_vals = [item for sublist in records.values() for item in sublist]
total_mean_fps = (sum([r['fps_mean'] for r in record_vals]) / len(record_vals))
total_mean_std = (sum([r['fps_std'] for r in record_vals]) / len(record_vals))
return (total_mean_fps, total_mean_std) |
def kronecker_product(a, b):
siz1 = torch.Size((torch.tensor(a.shape[(- 2):]) * torch.tensor(b.shape[(- 2):])))
res = (a.unsqueeze((- 1)).unsqueeze((- 3)) * b.unsqueeze((- 2)).unsqueeze((- 4)))
siz0 = res.shape[:(- 4)]
out = res.reshape((siz0 + siz1))
return out |
class PairClassifiers(nn.Module):
def __init__(self, fdim, num_classes):
super().__init__()
self.c1 = nn.Linear(fdim, num_classes)
self.c2 = nn.Linear(fdim, num_classes)
def forward(self, x):
z1 = self.c1(x)
if (not self.training):
return z1
z2 = self.... |
class PreActResNet(nn.Module):
def __init__(self, block, num_blocks, num_classes=200):
super(PreActResNet, self).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.layer1 = self._make_layer(block, 64, num_blocks[0], strid... |
def noam_schedule(step, warmup_step=4000):
if (step <= warmup_step):
return (step / warmup_step)
return ((warmup_step ** 0.5) * (step ** (- 0.5))) |
def parse_requirements(fname='requirements.txt', with_version=True):
import re
import sys
from os.path import exists
require_fpath = fname
def parse_line(line):
if line.startswith('-r '):
target = line.split(' ')[1]
for info in parse_require_file(target):
... |
def mixed_volume(mixture, points, checkin=True):
from phcpy.phcpy2c3 import py2c_celcon_initialize_supports as init
from phcpy.phcpy2c3 import py2c_celcon_set_type_of_mixture as setmix
from phcpy.phcpy2c3 import py2c_celcon_append_lifted_point as applft
from phcpy.phcpy2c3 import py2c_celcon_mixed_volum... |
def _check_model_old_version(model):
if hasattr(model.WN[0], 'res_layers'):
return True
else:
return False |
def icnr(x, scale=2, init=nn.init.kaiming_normal_):
(ni, nf, h, w) = x.shape
ni2 = int((ni / (scale ** 2)))
k = init(torch.zeros([ni2, nf, h, w])).transpose(0, 1)
k = k.contiguous().view(ni2, nf, (- 1))
k = k.repeat(1, 1, (scale ** 2))
k = k.contiguous().view([nf, ni, h, w]).transpose(0, 1)
... |
def setup_custom_environment(custom_module):
if custom_module.endswith('.py'):
module = _import_file('detectron2.utils.env.custom_module', custom_module)
else:
module = importlib.import_module(custom_module)
assert (hasattr(module, 'setup_environment') and callable(module.setup_environment))... |
def test_move_right(board: Board, another_board: Board) -> None:
(board, reward) = move_right(board)
expected_board = jnp.array([[0, 0, 0, 2], [0, 0, 2, 2], [0, 0, 1, 2], [0, 0, 0, 2]])
assert jnp.array_equal(board, expected_board)
assert (reward == 8)
(board, reward) = move_right(another_board)
... |
class Logger(object):
def __init__(self, filename):
self.terminal = sys.stdout
self.log = open(filename, 'a')
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass |
def prepare_within_day_indices_for_ground_truth(offset: int) -> np.ndarray:
return np.add([1, 2, 3, 6, 9, 12], (11 + offset)) |
class Metrics():
def __init__(self, residues: dict[(str, float)], isotope_error_range: list[int], cum_mass_threshold: float=0.5, ind_mass_threshold: float=0.1) -> None:
self.residues = residues
self.isotope_error_range = isotope_error_range
self.cum_mass_threshold = cum_mass_threshold
... |
def _dataset_exists(path, annotation, image_dir):
if (not osp.exists(path)):
logger.debug('Config dataset_dir {} is not exits, dataset config is not valid'.format(path))
return False
if annotation:
annotation_path = osp.join(path, annotation)
if (not osp.isfile(annotation_path)):... |
def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, use_tpu):
global_step = tf.train.get_or_create_global_step()
learning_rate = tf.constant(value=init_lr, shape=[], dtype=tf.float32)
learning_rate = tf.train.polynomial_decay(learning_rate, global_step, num_train_steps, end_learning_rate=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.