code stringlengths 101 5.91M |
|---|
_HEADS_REGISTRY.register()
class PointRendROIHeads(StandardROIHeads):
def __init__(self, cfg, input_shape):
super().__init__(cfg, input_shape)
self._init_mask_head(cfg, input_shape)
def _init_mask_head(self, cfg, input_shape):
self.mask_on = cfg.MODEL.MASK_ON
if (not self.mask_on... |
def get_random_entry_subset(entry_tuples, manualseed, subset_numimgs):
logger.debug('using manual random seed: {}'.format(manualseed))
random.seed(manualseed)
entry_random_subset = random.sample(entry_tuples, subset_numimgs)
logger.debug('subselected {} random images from total of {}:'.format(subset_num... |
def display_as_slider(*img_viewers):
def load_img(index=0):
for img_viewer in img_viewers:
display(Image(open(img_viewer.filenames[index], 'rb').read()))
interact(load_img, index=(0, (len(img_viewers[0].filenames) - 1))) |
class SMPL_DATA(data.Dataset):
def __init__(self, train, npoints=6890, shuffle_point=False):
self.train = train
self.shuffle_point = shuffle_point
self.npoints = npoints
self.path = './smpl_data/'
def __getitem__(self, index):
identity_mesh_i = np.random.randint(0, 16)
... |
class FasterRCNNNASFeatureExtractor(faster_rcnn_meta_arch.FasterRCNNFeatureExtractor):
def __init__(self, is_training, first_stage_features_stride, batch_norm_trainable=False, reuse_weights=None, weight_decay=0.0):
if (first_stage_features_stride != 16):
raise ValueError('`first_stage_features_s... |
class BinaryAccuracy(ZooKerasCreator, JavaValue):
def __init__(self, bigdl_type='float'):
super(BinaryAccuracy, self).__init__(None, bigdl_type) |
_module()
class MultiRotateAugOCR():
def __init__(self, transforms, rotate_degrees=None, force_rotate=False):
self.transforms = Compose(transforms)
self.force_rotate = force_rotate
if (rotate_degrees is not None):
self.rotate_degrees = (rotate_degrees if isinstance(rotate_degrees... |
def log_lamb_rs(optimizer: Optimizer, event_writer: SummaryWriter, token_count: int):
results = collections.defaultdict(list)
for group in optimizer.param_groups:
for p in group['params']:
state = optimizer.state[p]
for i in ('weight_norm', 'adam_norm', 'trust_ratio'):
... |
def score_cooked(allcomps, n=4, ground=0, smooth=1):
totalcomps = {'testlen': 0, 'reflen': 0, 'guess': ([0] * n), 'correct': ([0] * n)}
for comps in allcomps:
for key in ['testlen', 'reflen']:
totalcomps[key] += comps[key]
for key in ['guess', 'correct']:
for k in range(n... |
def test_doi_subdivisions():
ref_line = u'[10] A. Smith et al., "Introduction to Particle Physics", 2017, Springer Publishing, ISBN: , DOI: 10.978.819252/12214.'
res = get_references(ref_line)
references = res[0]
assert (references[0]['doi'] == [u'doi:10.978.819252/12214'])
assert (references[0]['li... |
class SharedEncoder(super_sac.nets.Encoder):
def __init__(self, dim):
super().__init__()
self._dim = dim
self.fc0 = nn.Linear(dim, 128)
self.fc1 = nn.Linear(128, dim)
def embedding_dim(self):
return self._dim
def forward(self, obs_dict):
x = F.relu(self.fc0(ob... |
def dobldobl_decomposition(deg):
from phcpy.phcpy2c3 import py2c_factor_number_of_dobldobl_components
from phcpy.phcpy2c3 import py2c_factor_witness_points_of_dobldobl_component
from phcpy.phcpy2c3 import py2c_factor_dobldobl_trace_sum_difference as dtf
nbcmp = py2c_factor_number_of_dobldobl_components(... |
def get(data_path, seed, fixed_order=False, pc_valid=0):
data = {}
taskcla = []
size = [1, 28, 28]
mean = (0.1307,)
std = (0.3081,)
dat = {}
dat['train'] = datasets.MNIST(data_path, train=True, download=True, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean, std... |
def conv3x3(in_planes, out_planes, kernel=3, strd=1, dilation=1, padding=1, bias=False):
return nn.Conv2d(in_planes, out_planes, kernel_size=kernel, dilation=dilation, stride=strd, padding=padding, bias=bias) |
def graph_propagation_soft(edges, score, max_sz, step=0.1, **kwargs):
edges = np.sort(edges, axis=1)
th = score.min()
score_dict = {}
for (i, e) in enumerate(edges):
score_dict[(e[0], e[1])] = score[i]
nodes = np.sort(np.unique(edges.flatten()))
mapping = ((- 1) * np.ones((nodes.max() + ... |
class KerasONNXRuntimeModel(ONNXRuntimeModel, KerasOptimizedModel):
def __init__(self, model, input_spec=None, onnxruntime_session_options=None, **export_kwargs):
KerasOptimizedModel.__init__(self)
with TemporaryDirectory() as tmpdir:
if isinstance(model, tf.keras.Model):
... |
def type_of_target(y, input_name=''):
valid = ((isinstance(y, Sequence) or issparse(y) or hasattr(y, '__array__')) and (not isinstance(y, str)))
if (not valid):
raise ValueError(('Expected array-like (array or non-string sequence), got %r' % y))
sparse_pandas = (y.__class__.__name__ in ['SparseSerie... |
class ScaledSolar(AbuModel):
version = '10000'
def _abu_massfrac_raw(self, scale):
scaled = ((self.sun * scale) + (self.bbn * (1 - scale)))
if (scale > 1.0):
(jj,) = np.argwhere((scaled.iso == isotope.ion('He4')))
bbn = ((self.sun * 0) + self.bbn)
for j in np.... |
def test_numeration_not_finding_year2():
ref_line = u'[138] Y.-B. Park, R. Mnig, and C. A. Volkert, Frequency effect on thermal fatigue damage in Cu interconnects, Thin Solid Films, vol. 515, pp. 3253 3258, 2007.'
res = get_references(ref_line)
references = res[0]
expected = [{'author': [u'Y.-B. Park, R... |
def li_regularizer(scale, scope=None):
import numbers
from tensorflow.python.framework import ops
from tensorflow.python.ops import standard_ops
if isinstance(scale, numbers.Integral):
raise ValueError(('scale cannot be an integer: %s' % scale))
if isinstance(scale, numbers.Real):
if... |
def test_shufflenetv2_unit():
data = torch.randn(1, 24, 56, 56)
inplanes = 24
planes = 116
stride = 2
branch_planes = (planes // 2)
downsample = nn.Sequential(nn.Conv2d(inplanes, branch_planes, kernel_size=3, stride=stride, padding=1, bias=False), nn.BatchNorm2d(branch_planes), nn.Conv2d(branch_... |
class TFStats(object):
def __init__(self):
self.raw_counts = {}
self.max_counts_for_term = {}
def get_term_frequency(self, term, doc, weighting_scheme='raw', normalization_factor=0.5):
if (weighting_scheme == 'binary'):
return (1 if ((term, doc) in self.raw_counts) else 0)
... |
('image-folder')
class ImageFolder(Dataset):
def __init__(self, root_path, split_file=None, split_key=None, first_k=None, repeat=1, cache='none'):
self.repeat = repeat
self.cache = cache
if (split_file is None):
filenames = sorted(os.listdir(root_path))
else:
... |
def chunked(seq: Sequence[_T], n: int) -> Iterable[Sequence[_T]]:
return (seq[i:(i + n)] for i in range(0, len(seq), n)) |
class TrainManager(object):
def __init__(self, student, teacher=None, train_loader=None, test_loader=None, train_config={}):
self.student = student
self.teacher = teacher
self.have_teacher = bool(self.teacher)
self.device = train_config['device']
self.name = train_config['nam... |
class SigmoidFlow(Flow):
def __init__(self, inverse=False):
super(SigmoidFlow, self).__init__(inverse)
def forward(self, input: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor)]:
out = input.sigmoid()
logdet = (F.softplus(input) + F.softplus((- input)))
logdet = (logdet.view(l... |
def test_VisualizeFCAMs():
import datetime as dt
import torch
import torch.nn.functional as F
seed = 0
torch.manual_seed(seed)
np.random.seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
debug_fd = join(root_dir, 'data/debug/input')
img_pil = Image.open(joi... |
def write_monomial_map(dim, ind, nbvar):
str_map = monomial_map_strings(dim, ind, nbvar)
print(str_map)
for str_var in str_map:
print(str_var) |
class Lang():
def __init__(self, name):
self.name = name
self.word2index = {'RE_DIGITS': 1, 'UNKNOWN': 2, 'PADDING': 0}
self.word2count = {'RE_DIGITS': 1, 'UNKNOWN': 1, 'PADDING': 1}
self.index2word = {0: 'PADDING', 1: 'RE_DIGITS', 2: 'UNKNOWN'}
self.n_words = 3
def addSe... |
def construct_mask(row_exs: List, col_exs: List=None) -> torch.tensor:
positive_on_diagonal = (col_exs is None)
num_row = len(row_exs)
col_exs = (row_exs if (col_exs is None) else col_exs)
num_col = len(col_exs)
row_entity_ids = torch.LongTensor([entity_dict.entity_to_idx(ex.tail_id) for ex in row_e... |
class DummyDataset(data.Dataset):
def __init__(self):
self.tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased')
self.sequence_a = 'intel-extension-for-transformers is based in SH'
self.sequence_b = 'Where is intel-extension-for-transformers based? NYC or SH'
self.enco... |
_module()
class TridentFasterRCNN(FasterRCNN):
'Implementation of `TridentNet <
def __init__(self, backbone: ConfigType, rpn_head: ConfigType, roi_head: ConfigType, train_cfg: ConfigType, test_cfg: ConfigType, neck: OptConfigType=None, data_preprocessor: OptConfigType=None, init_cfg: OptMultiConfig=None) -> Non... |
def conv_1x1_bn(inp, oup):
return nn.Sequential(Conv2d(inp, oup, 1, 1, 0, bias=False), BatchNorm2d(oup), nn.ReLU6(inplace=True)) |
class RLAv1p_ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):
super(RLAv1p_ResNet, self).__init__()
if (norm_layer is None):
... |
def _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config, delimiter='_', block_slice_pos=5):
all_keys = list(state_dict.keys())
sgm_patterns = ['input_blocks', 'middle_block', 'output_blocks']
is_in_sgm_format = False
for key in all_keys:
if any(((p in key) for p in sgm_patterns)):
... |
def write_tt(sentences, stream=sys.stdout):
for sentence in sentences:
for node in sentence['nodes']:
form = node['form']
negation = node.get('negation')
if (negation and len(negation)):
negation = negation[0]
if (not negation):
... |
def download_mnist(dirpath):
data_dir = os.path.join(dirpath, 'mnist')
if os.path.exists(data_dir):
print('Found MNIST - skip')
return
else:
os.mkdir(data_dir)
url_base = '
file_names = ['train-images-idx3-ubyte.gz', 'train-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz', ... |
def calc_distance_heuristic(gx, gy, ox, oy, resolution, rr):
goal_node = Node(round((gx / resolution)), round((gy / resolution)), 0.0, (- 1))
ox = [(iox / resolution) for iox in ox]
oy = [(ioy / resolution) for ioy in oy]
(obstacle_map, min_x, min_y, max_x, max_y, x_w, y_w) = calc_obstacle_map(ox, oy, r... |
def process(args):
root = Path(args.data_root).absolute()
lang = args.tgt_lang
cur_root = (root / f'en-{lang}')
if (not cur_root.is_dir()):
print(f'{cur_root.as_posix()} does not exist. Skipped.')
df = load_df_from_tsv((cur_root / f'{split}_raw_seg.tsv'))
train_text = []
for (_, row)... |
def GetResnetTransform():
x0 = x
x = BatchNormalization(momentum=0.9, name=('normalize_%d_%d' % (idx, j)))(x)
x = Activation('relu', name=('reluA_%d_%d' % (idx, j)))(x)
x = Conv2D(filters, kernel_size=[5, 5], strides=(1, 1), padding='same', name=('transformA_%d_%d' % (idx, j)))(x)
x = BatchNormaliza... |
def convert_xmod_checkpoint_to_pytorch(xmod_checkpoint_path: str, pytorch_dump_folder_path: str, classification_head: bool):
data_dir = Path('data_bin')
xmod = FairseqXmodModel.from_pretrained(model_name_or_path=str(Path(xmod_checkpoint_path).parent), checkpoint_file=Path(xmod_checkpoint_path).name, _name='xmod... |
def add_tagged_journal_in_place_of_IBID(previous_match):
return (' %s%s%s' % (CFG_REFEXTRACT_MARKER_OPENING_TITLE_IBID, previous_match['title'], CFG_REFEXTRACT_MARKER_CLOSING_TITLE_IBID)) |
class ProcessMonitor():
def __init__(self, process_infos, sc, ray_rdd, raycontext, verbose=False):
self.sc = sc
self.raycontext = raycontext
self.verbose = verbose
self.ray_rdd = ray_rdd
self.master = []
self.slaves = []
self.pgids = []
self.node_ips =... |
def generate_data_list():
annotation_root = '/media/heyonghao/HYH-4T-WD/public_dataset/Caltech/Caltech_new_annotations/anno_test_1xnew'
image_root = '/media/heyonghao/HYH-4T-WD/public_dataset/Caltech/Caltech_data/extracted_data'
list_file_path = './data_folder/data_list_caltech_test.txt'
if (not os.path... |
class SpatialGate(nn.Module):
def __init__(self):
super(SpatialGate, self).__init__()
self.conv = conv7x7_block(in_channels=2, out_channels=1, activation=None)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
att1 = x.max(dim=1)[0].unsqueeze(1)
att2 = x.mean(dim=1).unsqu... |
class KeypointTarget():
def __init__(self):
self.stride = cfg.TRAIN.STRIDE
self.radius = (cfg.TRAIN.OUTPUT_SIZE / 8)
self.std = (self.radius / 2)
if cfg.TRAIN.OFFSETS:
self.keypoints = np.zeros((2, cfg.TRAIN.OUTPUT_SIZE, cfg.TRAIN.OUTPUT_SIZE), dtype=np.float32)
... |
class StorageDevice(Device):
def __init__(self, capacity: float=None, efficiency: float=None, loss_coefficient: float=None, initial_soc: float=None, **kwargs: Any):
self.capacity = capacity
self.loss_coefficient = loss_coefficient
self.initial_soc = initial_soc
super().__init__(effic... |
def vocab_parallel_logit_helper(embed, lm_output):
if isinstance(lm_output, torch.Tensor):
lm_output = lm_output
elif isinstance(lm_output, tuple):
lm_output = lm_output[0]
else:
raise ValueError(f'Expect lm_output as tensor or tuple but get {type(lm_output)}')
lm_output = copy_t... |
def makeCluster(cluster):
print('subgraph cluster_{} {{\n\tcolor={};'.format(cluster, clusterColour[cluster]))
print('\tlabel = "{}";'.format(cluster))
for mod in mods:
if (mod[0] == cluster):
printNode(mod)
for (mod, data) in deps.items():
if (mod[0] != cluster):
... |
def load_train_history(jobs_dir, limit=None):
jobs = os.listdir(jobs_dir)
if limit:
matching = [d for d in jobs if (limit in d)]
else:
matching = jobs
dataframes = []
for job_dir in matching:
try:
df = load_model_info(jobs_dir, job_dir)
except (FileNotFoun... |
def draw_fig_2(cnndm_spec_name, xsum_spec_name):
fig = plt.figure(figsize=(FIG_SIZE_x, ysize_figure2))
draw_x_rel_postion_y_entropy(dir_datadrive, cnndm_spec_name, xsum_spec_name, SEPS=10, FIG_SIZE_x=GLOBAL_FIGURE_WIDTH)
fig.tight_layout()
plt.savefig(f'x_rel_postion_y_entropy{cnndm_spec_name}{xsum_spec... |
class Config(dict):
def __init__(self, filename=None):
assert os.path.exists(filename), "ERROR: Config File doesn't exist."
try:
with open(filename, 'r') as f:
self._cfg_dict = yaml.load(f, Loader)
except EnvironmentError:
logger.error('Please check th... |
def normalize_english(text):
def fn(m):
word = m.group()
if (word in english_dictionary):
return english_dictionary.get(word)
else:
return word
text = re.sub('([A-Za-z]+)', fn, text)
return text |
def require_pytesseract(test_case):
if (not is_pytesseract_available()):
return unittest.skip('test requires PyTesseract')(test_case)
else:
return test_case |
def TestExitCodeAndOutput(command):
p = gtest_test_utils.Subprocess(command)
Assert(p.exited)
AssertEq(1, p.exit_code)
Assert(('InitGoogleTest' in p.output)) |
class CommonMetricPrinter(EventWriter):
def __init__(self, max_iter):
self.logger = logging.getLogger(__name__)
self._max_iter = max_iter
def write(self):
storage = get_event_storage()
iteration = storage.iter
(data_time, time) = (None, None)
eta_string = 'N/A'
... |
class DenseLayer(Layer):
def __init__(self, input_layer, n_outputs, weights_std, init_bias_value, nonlinearity=rectify, dropout=0.0):
self.n_outputs = n_outputs
self.input_layer = input_layer
self.weights_std = numpy.float32(weights_std)
self.init_bias_value = numpy.float32(init_bias... |
class MultiHeadAttention(chainer.Chain):
def __init__(self, n_units, h=8, dropout=0.1, initialW=None, initial_bias=None):
super(MultiHeadAttention, self).__init__()
assert ((n_units % h) == 0)
stvd = (1.0 / np.sqrt(n_units))
with self.init_scope():
self.linear_q = L.Linea... |
def dump(obj, file=None, file_format=None, **kwargs):
if (file_format is None):
if is_str(file):
file_format = file.split('.')[(- 1)]
elif (file is None):
raise ValueError('file_format must be specified since file is None')
if (file_format not in file_handlers):
r... |
class TFConvBertModel(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class ReconnectingClient():
def __init__(self, address):
self.conn = None
self.address = address
logging.debug('Connecting...')
self.connect()
def connect(self):
while True:
try:
self.conn = multiprocessing.connection.Client(self.address)
... |
class VQA():
def __init__(self, annotation_file=None, question_file=None):
self.dataset = {}
self.questions = {}
self.qa = {}
self.qqa = {}
self.imgToQA = {}
if ((not (annotation_file is None)) and (not (question_file is None))):
dataset = json.load(open(a... |
def imputing_missing_features(df, target_name):
cat_col_names = get_category_columns(df, target_name)
num_cols_names = get_numerical_columns(df, target_name)
for col in cat_col_names:
df[col] = df[col].fillna('None')
for col in num_cols_names:
df[col] = df[col].fillna(df[col].mode()[0])
... |
.export
def get_lang_tok(lang: str, lang_tok_style: str, spec: str=LangTokSpec.main.value) -> str:
TOKEN_STYLES: Dict[(str, str)] = {LangTokStyle.mbart.value: '[{}]', LangTokStyle.multilingual.value: '__{}__'}
if spec.endswith('dae'):
lang = f'{lang}_dae'
elif spec.endswith('mined'):
lang = ... |
def main():
args = cfg.parse_args()
torch.cuda.manual_seed(args.random_seed)
_init_inception()
inception_path = check_or_download_inception(None)
create_inception_graph(inception_path)
gen_net = eval((('models_search.' + args.gen_model) + '.Generator'))(args=args).cuda()
dis_net = eval((('mo... |
.no_cover
.timeout(60)
def test_te_ppo_point():
assert (subprocess.run([str((EXAMPLES_ROOT_DIR / 'tf/te_ppo_point.py')), '--n_epochs', '1', '--batch_size_per_task', '100'], check=False).returncode == 0) |
def shared_convl1_bn_lrelu(shape, nb_filters, kernel, stride=(1, 1), **kwargs):
c = Convolution2D(nb_filters, kernel, padding='same', kernel_initializer='he_uniform', kernel_regularizer=l1(0.01), strides=(stride, stride), input_shape=shape)
b = BatchNormalization()
l = LeakyReLU()
return Sequential([c, ... |
def test_image_batch(model, images, new_gopro=False):
img_transforms = transforms.Compose([transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])])
size_transform = Compose([PadIfNeeded(736, 1280)])
images_ = read_imgs(images)
results_ = model(images_)
results_ = results_.cpu().float().nump... |
def prepare_data(datum, devices: list=None, allocation: list=None):
with torch.no_grad():
if (devices is None):
devices = (['cuda:0'] if args.cuda else ['cpu'])
if (allocation is None):
allocation = ([(args.batch_size // len(devices))] * (len(devices) - 1))
alloca... |
def shorten_to_bytes_width(string: str, maximum_bytes: int) -> str:
maximum_bytes = max(_MIN_WIDTH, maximum_bytes)
placeholder: str = '[...]'
encoded_placeholder = placeholder.encode().strip()
string = _RE_COMBINE_WHITESPACE.sub(' ', string)
string = _RE_STRIP_WHITESPACE.sub('', string)
encoded_... |
def get_centering_tf_schema(scale):
return [{'type': 'scalar-mult', 'value': (1 / scale)}, {'type': 'scalar-add', 'value': (- 0.5)}] |
def _check_same_shape(preds, targets):
if (preds.shape != targets.shape):
invalidInputError(False, 'preds and targets are expected to have the same shape') |
def get_config():
name = 'graph_correlated'
n_stages = 20
mu0 = (- 0.5)
sigma0 = 1
sigma_tilde = 1
agents = collections.OrderedDict([('coherent TS', functools.partial(CorrelatedBBTS, n_stages, mu0, sigma0, sigma_tilde)), ('misspecified TS', functools.partial(IndependentBBTS, n_stages, mu0, sigma... |
class DistributionOutput():
distribution_class: type
in_features: int
args_dim: Dict[(str, int)]
def __init__(self, dim: int=1) -> None:
self.dim = dim
self.args_dim = {k: (dim * self.args_dim[k]) for k in self.args_dim}
def _base_distribution(self, distr_args):
if (self.dim ... |
def scatter_sub(ref, indices, updates, use_locking=True, name=None):
if utils.is_kv_variable_op_type(ref.op.type):
return gen_kv_variable_ops.kv_variable_scatter_sub_v2(ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype), name=name)
return orignal_scatter_sub(ref, indices, updates, use_lockin... |
class TestGeneration(tf.test.TestCase):
def setUp(self):
self.net = WaveNetModel(batch_size=1, dilations=[1, 2, 4, 8, 16, 32, 64, 128, 256], filter_width=2, residual_channels=16, dilation_channels=16, quantization_channels=128, skip_channels=32)
def testGenerateSimple(self):
waveform = tf.placeh... |
def load_dataset(root_dir, train=True):
labels = []
images = []
if train:
sub_dir = 'training'
else:
sub_dir = 'test'
label_path = os.path.join(root_dir, sub_dir, 'label')
image_path = os.path.join(root_dir, sub_dir, 'images')
for file in glob.glob(os.path.join(image_path, '*... |
def idx_to_sparse(idx, sparse_dim):
sparse = np.zeros(sparse_dim)
sparse[int(idx)] = 1
return pd.Series(sparse, dtype=int) |
def get_args():
parse = argparse.ArgumentParser()
parse.add_argument('--gamma', type=float, default=0.99, help='the discount factor of RL')
parse.add_argument('--seed', type=int, default=123, help='the random seeds')
parse.add_argument('--num-workers', type=int, default=8, help='the number of workers to... |
class ParametricSequential(nn.Sequential):
def __init__(self, *args):
super(ParametricSequential, self).__init__(*args)
def forward(self, x, **kwargs):
for module in self._modules.values():
x = module(x, **kwargs)
return x |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = conv2d_circular(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = conv2... |
class FSMStage():
def __init__(self, stage_id: StageID, acting_agents: Sequence[AgentID], rewarded_agents: Optional[Sequence[AgentID]]=None, next_stages: Optional[Sequence[StageID]]=None, handler: Optional[Callable[([], StageID)]]=None) -> None:
self.id = stage_id
self.acting_agents = acting_agents
... |
def apply_patches(model, args):
if ((not args.custom_model) and (not args.custom_model_together) and (not args.custom_model_mistral)):
if ('GPTNeoXForCausalLM' in model.config.architectures):
assert (args.gpt_neox_max_length is not None)
patch_gptneox_for_longer_sequences(model, args... |
def test_amateur_draft() -> None:
result = amateur_draft(2019, 1)
assert (result is not None)
assert (not result.empty)
assert (len(result.columns) == 20)
assert (len(result) == 41) |
def resnet50_w1a2_imagenet(target_platform=None):
target_platform = resolve_target_platform(target_platform)
driver_mode = get_driver_mode()
model_name = 'resnet50-w1a2'
filename = find_bitfile(model_name, target_platform)
runtime_weight_dir = find_runtime_weights(model_name, target_platform)
re... |
def test__item_volume() -> None:
item_1 = Item(1, 0, 1)
item_2 = Item(1, 2, 2)
assert (item_volume(item_1) == 0)
assert (item_volume(item_2) == 4) |
class ACM(nn.Module):
def __init__(self, pool_scale, fusion, in_channels, channels, conv_cfg, norm_cfg, act_cfg):
super(ACM, self).__init__()
self.pool_scale = pool_scale
self.fusion = fusion
self.in_channels = in_channels
self.channels = channels
self.conv_cfg = conv... |
class Exp(ZooKerasLayer):
def __init__(self, input_shape=None, **kwargs):
super(Exp, self).__init__(None, (list(input_shape) if input_shape else None), **kwargs) |
class ConditionalDetrPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def auprc_compute_fn(y_preds, y_targets):
y_true = y_targets.numpy()
y_pred = y_preds.numpy()
return average_precision_score(y_true, y_pred) |
class MultiScaleArchitecture(Flow):
def __init__(self, flow_step, levels, num_steps, in_channels, factors, hidden_channels, h_channels=0, inverse=False, transform='affine', prior_transform='affine', alpha=1.0, kernel_size=None, coupling_type='conv', h_type=None, activation='relu', normalize=None, num_groups=None):
... |
class FiveCrop(object):
def __init__(self, size):
self.size = size
if isinstance(size, numbers.Number):
self.size = (int(size), int(size))
else:
assert (len(size) == 2), 'Please provide only two dimensions (h, w) for size.'
self.size = size
def __call_... |
def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs):
required = {}
for linenum in xrange(clean_lines.NumLines()):
line = clean_lines.elided[linenum]
if ((not line) or (line[0] == '#')):
continue
matched = _RE_PATTERN_STRING.search(line)
... |
def eval_score(prediction, ground_truth):
(precision, recall, f1) = (0, 0, 0)
if (len(ground_truth) == 0):
if (len(prediction) == 0):
(EM, precision, recall, f1) = (1, 1, 1, 1)
else:
EM = (normalize_answer(prediction) == normalize_answer(ground_truth))
prediction_tokens =... |
def mask_bg(mask, attention, threshold=0.05):
pos_bg = (attention < threshold)
mask[pos_bg.data] = 0.0
return mask |
def find_smallest_n(m, t, max_iters=100):
for n in range((m + 1), (m + max_iters)):
if check_configuration(m, n, t):
return n
print('Failed to find valid N!')
return (- 1) |
def batch_decode(encoded_boxes, box_coder, anchors):
encoded_boxes.get_shape().assert_has_rank(3)
if (encoded_boxes.get_shape()[1].value != anchors.num_boxes_static()):
raise ValueError(('The number of anchors inferred from encoded_boxes and anchors are inconsistent: shape[1] of encoded_boxes %s should ... |
class FastAdaptiveAvgPool2d(nn.Module):
def __init__(self, flatten=False):
super(FastAdaptiveAvgPool2d, self).__init__()
self.flatten = flatten
def forward(self, x):
return (x.mean((2, 3)) if self.flatten else x.mean((2, 3), keepdim=True)) |
def set_gpu_fraction(sess=None, gpu_fraction=0.3):
print((' tensorlayer: GPU MEM Fraction %f' % gpu_fraction))
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
return sess |
def cross_entropy_smooth(input, target, size_average=True, label_smoothing=0.1):
y = torch.eye(10).cuda()
lb_oh = y[target]
target = ((lb_oh * (1 - label_smoothing)) + (0.5 * label_smoothing))
logsoftmax = nn.LogSoftmax()
if size_average:
return torch.mean(torch.sum(((- target) * logsoftmax(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.