code
stringlengths
281
23.7M
class DenseUnit(nn.Module): def __init__(self, in_channels, out_channels, dropout_rate): super(DenseUnit, self).__init__() self.use_dropout = (dropout_rate != 0.0) bn_size = 4 inc_channels = (out_channels - in_channels) mid_channels = (inc_channels * bn_size) self.conv1 = pre_conv1x1_block(in_channels=in_channels, out_channels=mid_channels) self.conv2 = pre_conv3x3_block(in_channels=mid_channels, out_channels=inc_channels) if self.use_dropout: self.dropout = nn.Dropout(p=dropout_rate) def forward(self, x): identity = x x = self.conv1(x) x = self.conv2(x) if self.use_dropout: x = self.dropout(x) x = torch.cat((identity, x), dim=1) return x
def test_inference_without_dataset_info(): pose_model = init_pose_model('configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/res50_coco_256x192.py', None, device='cpu') if ('dataset_info' in pose_model.cfg): _ = pose_model.cfg.pop('dataset_info') image_name = 'tests/data/coco/.jpg' person_result = [] person_result.append({'bbox': [50, 50, 50, 100]}) with pytest.warns(DeprecationWarning): (pose_results, _) = inference_top_down_pose_model(pose_model, image_name, person_result, format='xywh') with pytest.warns(DeprecationWarning): vis_pose_result(pose_model, image_name, pose_results) with pytest.raises(NotImplementedError): with pytest.warns(DeprecationWarning): (pose_results, _) = inference_top_down_pose_model(pose_model, image_name, person_result, format='xywh', dataset='test') pose_model = init_pose_model('configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_512x512.py', None, device='cpu') if ('dataset_info' in pose_model.cfg): _ = pose_model.cfg.pop('dataset_info') image_name = 'tests/data/coco/.jpg' with pytest.warns(DeprecationWarning): (pose_results, _) = inference_bottom_up_pose_model(pose_model, image_name) with pytest.warns(DeprecationWarning): vis_pose_result(pose_model, image_name, pose_results) pose_model = init_pose_model('configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/res50_coco_256x192.py', None, device='cpu') if ('dataset_info' in pose_model.cfg): _ = pose_model.cfg.pop('dataset_info') image_name = 'tests/data/coco/.jpg' person_result = [{'bbox': [50, 50, 50, 100]}] with pytest.warns(DeprecationWarning): (pose_results, _) = inference_top_down_pose_model(pose_model, image_name, person_result, format='xywh') (pose_results, _) = get_track_id(pose_results, [], next_id=0) with pytest.warns(DeprecationWarning): vis_pose_tracking_result(pose_model, image_name, pose_results) with pytest.raises(NotImplementedError): with pytest.warns(DeprecationWarning): vis_pose_tracking_result(pose_model, image_name, pose_results, dataset='test') pose_model = init_pose_model('configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_512x512.py', None, device='cpu') if ('dataset_info' in pose_model.cfg): _ = pose_model.cfg.pop('dataset_info') image_name = 'tests/data/coco/.jpg' with pytest.warns(DeprecationWarning): (pose_results, _) = inference_bottom_up_pose_model(pose_model, image_name) (pose_results, next_id) = get_track_id(pose_results, [], next_id=0) with pytest.warns(DeprecationWarning): vis_pose_tracking_result(pose_model, image_name, pose_results, dataset='BottomUpCocoDataset') pose_model = init_pose_model('configs/body/3d_kpt_sview_rgb_img/pose_lift/h36m/simplebaseline3d_h36m.py', None, device='cpu') pose_det_result = {'keypoints': np.zeros((17, 3)), 'bbox': [50, 50, 50, 50], 'track_id': 0, 'image_name': 'tests/data/h36m/S1_Directions_1._000001.jpg'} if ('dataset_info' in pose_model.cfg): _ = pose_model.cfg.pop('dataset_info') pose_results_2d = [[pose_det_result]] dataset = pose_model.cfg.data['test']['type'] pose_results_2d = extract_pose_sequence(pose_results_2d, frame_idx=0, causal=False, seq_len=1, step=1) with pytest.warns(DeprecationWarning): _ = inference_pose_lifter_model(pose_model, pose_results_2d, dataset, with_track_id=False) with pytest.warns(DeprecationWarning): pose_lift_results = inference_pose_lifter_model(pose_model, pose_results_2d, dataset, with_track_id=True) for res in pose_lift_results: res['title'] = 'title' with pytest.warns(DeprecationWarning): vis_3d_pose_result(pose_model, pose_lift_results, img=pose_results_2d[0][0]['image_name'], dataset=dataset) with pytest.raises(NotImplementedError): with pytest.warns(DeprecationWarning): _ = inference_pose_lifter_model(pose_model, pose_results_2d, dataset='test')
class Controls(dict): _buttons = ('mouse1', 'mouse2', 'mouse3', 'mouse4', 'mouse5', 'wheel') _buttons += ('arrowleft', 'arrowright', 'arrowup', 'arrowdown') _buttons += ('tab', 'enter', 'escape', 'backspace', 'delete') _buttons += ('shift', 'control') _modes = ('drag', 'push', 'peek', 'repeat') def __init__(self, *actions): self._actions = tuple(actions) def __repr__(self): if (not self): return '{}' s = '{' for (key, action_tuple) in self.items(): s += f''' '{key}': {repr(action_tuple)},''' s += '\n}' return s def action_names(self): return self._actions def __setitem__(self, key, action_tuple): if (not isinstance(key, str)): raise TypeError('Controls key must be str') (*modifiers, button) = key.split('+') modifiers = sorted([m.lower() for m in modifiers]) button = button.lower() for m in modifiers: if (m not in ('shift', 'control', 'alt')): raise ValueError(f"Invalid key modifier '{m}'") if (len(button) == 1): pass elif (button not in self._buttons): raise ValueError(f"Invalid button/key '{button}', pick a char, or one of {self._buttons}") if (not (isinstance(action_tuple, (list, tuple)) and (len(action_tuple) == 3))): raise TypeError('Controls action must be 3-element tuples') (action, mode, multiplier) = action_tuple if (action not in self._actions): raise ValueError(f"Invalid action '{action}', pick one of {self._actions}") if (mode not in self._modes): raise ValueError(f"Invalid mode '{mode}', pick one of {self._modes}") if ((mode == 'drag') and (not button.startswith('mouse'))): raise ValueError('Drag mode only allowed for mouse buttons.') if ((button == 'wheel') and (mode != 'push')): raise ValueError("Only mode 'push' allowed with 'wheel'.") if isinstance(multiplier, (int, float)): multiplier = float(multiplier) elif isinstance(multiplier, (list, tuple)): multiplier = tuple((float(x) for x in multiplier)) elif isinstance(multiplier, np.ndarray): if (multiplier.size == 1): multiplier = float(multiplier) else: multiplier = tuple((float(x) for x in multiplier)) modifiers_prefix = '+'.join((modifiers + [''])) key = (modifiers_prefix + button) super().__setitem__(key, (action, mode, multiplier)) def setdefault(self, key, default): if (key not in self): self[key] = default return self[key] def update(self, e, **f): for (k, v) in e.items(): self[k] = v for (k, v) in f.items(): self[k] = v
class Fnode(nn.Module): def __init__(self, combine: nn.Module, after_combine: nn.Module): super(Fnode, self).__init__() self.combine = combine self.after_combine = after_combine def forward(self, x: List[torch.Tensor]) -> torch.Tensor: return self.after_combine(self.combine(x))
def Parser(): parser = argparse.ArgumentParser() parser.add_argument('--root', type=str, default='../data/example_data', help='rio path') parser.add_argument('--type', type=str, default='train', choices=['train', 'test', 'validation'], help='allow multiple rel pred outputs per pair', required=False) parser.add_argument('--txt', type=str, default='"../data/train_scans.txt"', help='path to the txt file contain scan ids', required=False) return parser
def test_tb05ad_resonance(): A = np.array([[0, (- 1)], [1, 0]]) B = np.array([[1], [0]]) C = np.array([[0, 1]]) jomega = 1j with pytest.raises(SlycotArithmeticError, match='Either `freq`.* is too near to an eigenvalue of A,\\nor `rcond` is less than the machine precision EPS.') as cm: transform.tb05ad(2, 1, 1, jomega, A, B, C, job='NH') assert (cm.value.info == 2)
def make_talabel_seg_list(utt_index_list, utt_list, utt_len_list, seg_len, utt2talabels): seg_list = [] for utt_index in utt_index_list: utt_id = utt_list[utt_index] utt_len = utt_len_list[utt_index] utt_segs = [talabel.get_centered_seg(seg_len, max_t=utt_len) for talabel in utt2talabels[utt_id]] seg_list += [Segment(utt_id, seg[0], seg[1], seg[2]) for seg in utt_segs if (seg is not None)] return seg_list
class FSThread(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None): super().__init__(group=group, target=target, name=name, args=args, kwargs=kwargs, daemon=daemon) self.err = None def check_and_raise_error(self): if (not self.err): return logger.debug('Thread error caught: %s', self.err) raise self.err[1].with_traceback(self.err[2]) def run(self): try: if self._target: self._target(*self._args, **self._kwargs) except Exception as err: self.err = sys.exc_info() logger.debug('Error in thread (%s): %s', self._name, str(err)) finally: del self._target, self._args, self._kwargs
def test_fix_ansi_codes_for_github_actions(): input = textwrap.dedent('\n This line is normal\n \x1b[1mThis line is bold\n This line is also bold\n \x1b[31m this line is red and bold\n This line is red and bold, too\x1b[0m\n This line is normal again\n ') expected = textwrap.dedent('\n This line is normal\n \x1b[1mThis line is bold\n \x1b[1mThis line is also bold\n \x1b[1m\x1b[31m this line is red and bold\n \x1b[1m\x1b[31mThis line is red and bold, too\x1b[0m\n This line is normal again\n ') output = fix_ansi_codes_for_github_actions(input) assert (output == expected)
def test_assertrepr_loaded_per_dir(pytester: Pytester) -> None: pytester.makepyfile(test_base=['def test_base(): assert 1 == 2']) a = pytester.mkdir('a') a.joinpath('test_a.py').write_text('def test_a(): assert 1 == 2', encoding='utf-8') a.joinpath('conftest.py').write_text('def pytest_assertrepr_compare(): return ["summary a"]', encoding='utf-8') b = pytester.mkdir('b') b.joinpath('test_b.py').write_text('def test_b(): assert 1 == 2', encoding='utf-8') b.joinpath('conftest.py').write_text('def pytest_assertrepr_compare(): return ["summary b"]', encoding='utf-8') result = pytester.runpytest() result.stdout.fnmatch_lines(['*def test_a():*', '*E*assert summary a*', '*def test_b():*', '*E*assert summary b*', '*def test_base():*', '*E*assert 1 == 2*'])
def make_os_version_info(archbits: int, *, wide: bool): Struct = struct.get_aligned_struct(archbits) char_type = (ctypes.c_wchar if wide else ctypes.c_char) class OSVERSIONINFO(Struct): _fields_ = (('dwOSVersionInfoSize', ctypes.c_uint32), ('dwMajorVersion', ctypes.c_uint32), ('dwMinorVersion', ctypes.c_uint32), ('dwBuildNumber', ctypes.c_uint32), ('dwPlatformId', ctypes.c_uint32), ('szCSDVersion', (char_type * 128))) return OSVERSIONINFO
def plot_err_with_without_post_process(fig=None, ax_arr=None, big_ax=None, dpi=300, figsize=(2.83, 5.5)): if ((fig is None) and (ax_arr is None)): (fig, ax_arr) = plt.subplots(2, 1, dpi=dpi, figsize=figsize) metrics = ['avg_error', 'avg_segment_error_rate'] for ax_ in ax_arr.flatten(): ax_.tick_params(pad=0.1) if (big_ax is None): big_ax = fig.add_subplot(111, frameon=False) big_ax.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False) big_ax.grid(False) ylabels = ['Frame\nerror (%)', 'Syllable\nerror rate (%)'] species = ['Bengalese Finches', 'Canaries'] for (metric, ylabel) in zip(metrics, ylabels): if (metric == 'avg_error'): row = 0 elif (metric == 'avg_segment_error_rate'): row = 1 ax = ax_arr[row] if (row == 0): legend = False elif (row == 1): legend = True g = sns.lineplot(x='train_set_dur_ind', y=metric, data=curve_df, ci=None, hue='Species', palette=SPECIES_PALETTE, style='Post-processing', linewidth=2, ax=ax, legend=legend) if legend: (handles, labels) = ax.get_legend_handles_labels() g.legend_.remove() ylabel_text = ax.set_ylabel(ylabel) if (row == 0): ax.set_xlabel('') elif (row == 1): ax.set_xlabel('Training set duration') ax.set_xticks(list(dur_int_map.values())) ax.set_xticklabels([]) ax_arr[0].set_ylim(0, 6) ax_arr[1].set_ylim(0, 15) curve_df_for_arrow = curve_df[((curve_df.Species == 'Canaries') & (curve_df['Post-processing'] == 'with'))] max_train_set_dur_ind = curve_df_for_arrow.train_set_dur_ind.max() mean_frame_err_max_dur = curve_df_for_arrow[(curve_df_for_arrow.train_set_dur_ind == max_train_set_dur_ind)]['avg_error'].mean() ax_arr[0].annotate('Max. train dur.', xy=(max_train_set_dur_ind, mean_frame_err_max_dur), xytext=((max_train_set_dur_ind - 4.0), (mean_frame_err_max_dur + 2.0)), arrowprops={'arrowstyle': '->', 'lw': 1, 'color': 'black'}, va='center', fontsize=10) sns.despine(fig) big_ax.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False) big_ax.grid(False) big_ax.legend(handles, labels, loc='upper right', bbox_to_anchor=[1.0, (- 0.075)]) return (fig, ax_arr)
def get_video_trans(): train_trans = video_transforms.Compose([video_transforms.RandomHorizontalFlip(), video_transforms.Resize((200, 112)), video_transforms.RandomCrop(112), volume_transforms.ClipToTensor(), video_transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]) test_trans = video_transforms.Compose([video_transforms.Resize((200, 112)), video_transforms.CenterCrop(112), volume_transforms.ClipToTensor(), video_transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]) return (train_trans, test_trans)
def test_local_variables_should_be_displayed_when_showlocals_option_is_used(pytester): pytester.makefile('.feature', test=FEATURE) pytester.makepyfile(textwrap.dedent(' from pytest_bdd import given, when, then, scenario\n\n\n (\'there is a bar\')\n def _():\n return \'bar\'\n\n (\'the bar is accessed\')\n def _():\n pass\n\n\n (\'world explodes\')\n def _():\n local_var = "MULTIPASS"\n raise Exception("BIGBADABOOM")\n\n\n (\'test.feature\', \'Scenario example 1\')\n def test_scenario_1():\n pass\n ')) result = pytester.runpytest('--gherkin-terminal-reporter', '--showlocals') result.assert_outcomes(passed=0, failed=1) result.stdout.fnmatch_lines('request*=*<FixtureRequest for *') result.stdout.fnmatch_lines('local_var*=*MULTIPASS*')
class TesttestMatIO(): def setup_method(self): self.test_file = test_file = pysal_examples.get_path('spat-sym-us.mat') self.obj = MatIO(test_file, 'r') def test_close(self): f = self.obj f.close() pytest.raises(ValueError, f.read) def test_read(self): w = self.obj.read() assert (w.n == 46) assert (w.mean_neighbors == 4.) assert ([1.0, 1.0, 1.0, 1.0] == list(w[1].values())) def test_seek(self): self.test_read() pytest.raises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() def test_write(self): w = self.obj.read() f = tempfile.NamedTemporaryFile(suffix='.mat') fname = f.name f.close() o = FileIO(fname, 'w') with warnings.catch_warnings(record=True) as warn: warnings.simplefilter('always') o.write(w) if (len(warn) > 0): assert issubclass(warn[0].category, FutureWarning) o.close() wnew = FileIO(fname, 'r').read() assert (wnew.pct_nonzero == w.pct_nonzero) os.remove(fname)
class GenericBase(CommonBaseTesting): fake_ctrl = CommonBase.control('C{ch}:control?', 'C{ch}:control %d', 'docs', validator=truncated_range, values=(1, 10), dynamic=True) fake_setting = CommonBase.setting('C{ch}:setting %d', 'docs', validator=truncated_range, values=(1, 10), dynamic=True) fake_measurement = CommonBase.measurement('C{ch}:measurement?', 'docs', values={'X': 1, 'Y': 2, 'Z': 3}, map_values=True, dynamic=True) special_control = CommonBase.control('SOUR{ch}:special?', 'OUTP{ch}:special %s', 'A special control with different channel specifiers for get and set.', cast=str)
class _MSDataLoaderIter(_DataLoaderIter): def __init__(self, loader): self.dataset = loader.dataset self.scale = loader.scale self.collate_fn = loader.collate_fn self.batch_sampler = loader.batch_sampler self.num_workers = loader.num_workers self.pin_memory = (loader.pin_memory and torch.cuda.is_available()) self.timeout = loader.timeout self.sample_iter = iter(self.batch_sampler) base_seed = torch.LongTensor(1).random_().item() if (self.num_workers > 0): self.worker_init_fn = loader.worker_init_fn self.worker_queue_idx = 0 self.worker_result_queue = multiprocessing.Queue() self.batches_outstanding = 0 self.worker_pids_set = False self.shutdown = False self.send_idx = 0 self.rcvd_idx = 0 self.reorder_dict = {} self.done_event = multiprocessing.Event() base_seed = torch.LongTensor(1).random_()[0] self.index_queues = [] self.workers = [] for i in range(self.num_workers): index_queue = multiprocessing.Queue() index_queue.cancel_join_thread() w = multiprocessing.Process(target=_ms_loop, args=(self.dataset, index_queue, self.worker_result_queue, self.done_event, self.collate_fn, self.scale, (base_seed + i), self.worker_init_fn, i)) w.daemon = True w.start() self.index_queues.append(index_queue) self.workers.append(w) if self.pin_memory: self.data_queue = queue.Queue() pin_memory_thread = threading.Thread(target=_utils.pin_memory._pin_memory_loop, args=(self.worker_result_queue, self.data_queue, torch.cuda.current_device(), self.done_event)) pin_memory_thread.daemon = True pin_memory_thread.start() self.pin_memory_thread = pin_memory_thread else: self.data_queue = self.worker_result_queue _utils.signal_handling._set_worker_pids(id(self), tuple((w.pid for w in self.workers))) _utils.signal_handling._set_SIGCHLD_handler() self.worker_pids_set = True for _ in range((2 * self.num_workers)): self._put_indices()
def test_linop_no_init_err(): mat = torch.rand((3, 1, 2)) x = torch.rand(2) linop = LinOpWithoutInit(mat) try: y = linop.mv(x) msg = 'A RuntimeError must be raised when a LinearOperator is called without .__init__() called first' assert False, msg except RuntimeError as e: assert ('__init__' in str(e)), 'The error message must contain "__init__"'
class StateSelect(widgets.Select): def render(self, name, value, attrs=None, *args, **kwargs): if isinstance(value, base.StateWrapper): state_name = value.state.name elif isinstance(value, base.State): state_name = value.name else: state_name = str(value) return super(StateSelect, self).render(name, state_name, attrs, *args, **kwargs)
def _get_reader_kwargs(reader, reader_kwargs): reader_kwargs = (reader_kwargs or {}) if (reader is None): reader_kwargs = {None: reader_kwargs} elif (reader_kwargs.keys() != set(reader)): reader_kwargs = dict.fromkeys(reader, reader_kwargs) reader_kwargs_without_filter = {} for (k, v) in reader_kwargs.items(): reader_kwargs_without_filter[k] = v.copy() reader_kwargs_without_filter[k].pop('filter_parameters', None) return (reader_kwargs, reader_kwargs_without_filter)
def test_interleave_with_mask(): a = np.arange(6) b = np.arange(6, 12) c = np.arange(12, 18) assert (a.shape[0] == b.shape[0] == c.shape[0]) n = a.shape[0] a_buf = np.empty((n * INT32_BUF_SIZE), dtype=np.uint8) b_buf = np.empty((n * INT32_BUF_SIZE), dtype=np.uint8) c_buf = np.empty((n * INT32_BUF_SIZE), dtype=np.uint8) indexes = np.empty((3, (n + 1)), dtype=np.int32) a_p = vcf_ints_to_byte_buf(a_buf, 0, a, indexes[0]) b_p = vcf_ints_to_byte_buf(b_buf, 0, b, indexes[1]) c_p = vcf_ints_to_byte_buf(c_buf, 0, c, indexes[2]) a_ch = a_buf[:a_p] b_ch = b_buf[:b_p] c_ch = c_buf[:c_p] assert (byte_buf_to_str(a_ch) == '012345') assert (byte_buf_to_str(b_ch) == '') assert (byte_buf_to_str(c_ch) == '') buf_size = interleave_buf_size(indexes, a_buf, b_buf, c_buf) buf = np.empty(buf_size, dtype=np.uint8) mask = np.array([False, True, False]) p = interleave(buf, 0, indexes, mask, ord(':'), ord(' '), a_buf, b_buf, c_buf) buf = buf[:p] assert (byte_buf_to_str(buf) == '0:12 1:13 2:14 3:15 4:16 5:17')
def stack_images_PIL(imgs, shape=None, individual_img_size=None): assert (len(imgs) > 0), 'No images received.' if (shape is None): size = int(np.ceil(np.sqrt(len(imgs)))) shape = [int(np.ceil((len(imgs) / size))), size] else: if isinstance(shape, numbers.Number): shape = (2 * [shape]) assert (len(shape) == 2), 'Shape should specify (width, height).' if (individual_img_size is None): for i in range((len(imgs) - 1)): assert (imgs[i].size == imgs[(i + 1)].size), (('Images are of different sizes, please specify a ' + 'size (width, height). Found sizes:\n') + ', '.join((str(img.size) for img in imgs))) individual_img_size = imgs[0].size else: if (not isinstance(individual_img_size, (tuple, list))): individual_img_size = (2 * (individual_img_size,)) individual_img_size = tuple(individual_img_size) for i in range(len(imgs)): if (imgs[i].size != individual_img_size): imgs[i] = imgs[i].resize(individual_img_size) (width, height) = individual_img_size (width, height) = (int(width), int(height)) canvas = Image.new('RGB', ((shape[0] * width), (shape[1] * height)), (0, 0, 0, 0)) imgs = imgs.copy() for h_i in range(shape[1]): for w_i in range(shape[0]): if (len(imgs) > 0): img = imgs.pop(0).convert('RGB') offset = ((w_i * width), (h_i * height)) canvas.paste(img, offset) return canvas
class _MultipleMatch(ParseElementEnhance): def __init__(self, expr, stopOn=None): super().__init__(expr) self.saveAsList = True ender = stopOn if isinstance(ender, str_type): ender = self._literalStringClass(ender) self.stopOn(ender) def stopOn(self, ender): if isinstance(ender, str_type): ender = self._literalStringClass(ender) self.not_ender = ((~ ender) if (ender is not None) else None) return self def parseImpl(self, instring, loc, doActions=True): self_expr_parse = self.expr._parse self_skip_ignorables = self._skipIgnorables check_ender = (self.not_ender is not None) if check_ender: try_not_ender = self.not_ender.tryParse if check_ender: try_not_ender(instring, loc) (loc, tokens) = self_expr_parse(instring, loc, doActions, callPreParse=False) try: hasIgnoreExprs = (not (not self.ignoreExprs)) while 1: if check_ender: try_not_ender(instring, loc) if hasIgnoreExprs: preloc = self_skip_ignorables(instring, loc) else: preloc = loc (loc, tmptokens) = self_expr_parse(instring, preloc, doActions) if (tmptokens or tmptokens.haskeys()): tokens += tmptokens except (ParseException, IndexError): pass return (loc, tokens) def _setResultsName(self, name, listAllMatches=False): if __diag__.warn_ungrouped_named_tokens_in_collection: for e in ([self.expr] + getattr(self.expr, 'exprs', [])): if (isinstance(e, ParserElement) and e.resultsName): warnings.warn('{}: setting results name {!r} on {} expression collides with {!r} on contained expression'.format('warn_ungrouped_named_tokens_in_collection', name, type(self).__name__, e.resultsName), stacklevel=3) return super()._setResultsName(name, listAllMatches)
class TransformerLanguageModelConfig(FairseqDataclass): activation_fn: ChoiceEnum(utils.get_available_activation_fns()) = field(default='relu', metadata={'help': 'activation function to use'}) dropout: float = field(default=0.1, metadata={'help': 'dropout probability'}) attention_dropout: float = field(default=0.0, metadata={'help': 'dropout probability for attention weights'}) activation_dropout: float = field(default=0.0, metadata={'help': 'dropout probability after activation in FFN.'}) relu_dropout: float = field(default=0.0, metadata={'help': 'dropout probability after activation in FFN.'}) decoder_embed_dim: int = field(default=512, metadata={'help': 'decoder embedding dimension'}) decoder_output_dim: int = field(default=512, metadata={'help': 'decoder output dimension'}) decoder_input_dim: int = field(default=512, metadata={'help': 'decoder input dimension'}) decoder_ffn_embed_dim: int = field(default=2048, metadata={'help': 'decoder embedding dimension for FFN'}) decoder_layers: int = field(default=6, metadata={'help': 'num decoder layers'}) decoder_attention_heads: int = field(default=8, metadata={'help': 'num decoder attention heads'}) decoder_normalize_before: bool = field(default=False, metadata={'help': 'apply layernorm before each decoder block'}) no_decoder_final_norm: bool = field(default=False, metadata={'help': "don't add an extra layernorm after the last decoder block"}) adaptive_softmax_cutoff: Optional[str] = field(default=None, metadata={'help': 'comma separated list of adaptive softmax cutoff points. Must be used with adaptive_loss criterion'}) adaptive_softmax_dropout: float = field(default=0, metadata={'help': 'sets adaptive softmax dropout for the tail projections'}) adaptive_softmax_factor: float = field(default=4, metadata={'help': 'adaptive input factor'}) no_token_positional_embeddings: bool = field(default=False, metadata={'help': 'if set, disables positional embeddings (outside self attention)'}) share_decoder_input_output_embed: bool = field(default=False, metadata={'help': 'share decoder input and output embeddings'}) character_embeddings: bool = field(default=False, metadata={'help': 'if set, uses character embedding convolutions to produce token embeddings'}) character_filters: str = field(default='[(1, 64), (2, 128), (3, 192), (4, 256), (5, 256), (6, 256), (7, 256)]', metadata={'help': 'size of character embeddings'}) character_embedding_dim: int = field(default=4, metadata={'help': 'size of character embeddings'}) char_embedder_highway_layers: int = field(default=2, metadata={'help': 'number of highway layers for character token embeddder'}) adaptive_input: bool = field(default=False, metadata={'help': 'if set, uses adaptive input'}) adaptive_input_factor: float = field(default=4, metadata={'help': 'adaptive input factor'}) adaptive_input_cutoff: Optional[str] = field(default=None, metadata={'help': 'comma separated list of adaptive input cutoff points.'}) tie_adaptive_weights: bool = field(default=False, metadata={'help': 'if set, ties the weights of adaptive softmax and adaptive input'}) tie_adaptive_proj: bool = field(default=False, metadata={'help': 'if set, ties the projection weights of adaptive softmax and adaptive input'}) decoder_learned_pos: bool = field(default=False, metadata={'help': 'use learned positional embeddings in the decoder'}) decoder_layerdrop: float = field(default=0.0, metadata={'help': 'LayerDrop probability for decoder'}) decoder_layers_to_keep: Optional[str] = field(default=None, metadata={'help': 'which layers to *keep* when pruning as a comma-separated list'}) layernorm_embedding: bool = field(default=False, metadata={'help': 'add layernorm to embedding'}) no_scale_embedding: bool = field(default=False, metadata={'help': 'if True, dont scale embeddings'}) checkpoint_activations: bool = field(default=False, metadata={'help': 'checkpoint activations at each layer'}) quant_noise_pq: float = field(default=0.0, metadata={'help': 'iterative PQ quantization noise at training time'}) quant_noise_pq_block_size: int = field(default=8, metadata={'help': 'block size of quantization noise at training time'}) quant_noise_scalar: float = field(default=0.0, metadata={'help': 'scalar quantization noise and scalar quantization at training time'}) add_bos_token: bool = II('task.add_bos_token') tokens_per_sample: int = II('task.tokens_per_sample') max_target_positions: Optional[int] = II('task.max_target_positions') tpu: bool = II('common.tpu')
def all_coarse_grains_for_blackbox(blackbox): for partition in all_partitions(blackbox.output_indices): for grouping in all_groupings(partition): coarse_grain = CoarseGrain(partition, grouping) try: validate.blackbox_and_coarse_grain(blackbox, coarse_grain) except ValueError: continue (yield coarse_grain)
def alexandrov(space: LengthSpace, pt_a: Point, pt_b: Point, pt_c: Point) -> Scalar: pt_d = midpoint(space, pt_a, pt_c) bisector_lenth = space.length(pt_b, pt_d) euclidean_bisector_length = _bisector_length(space.length(pt_a, pt_b), space.length(pt_b, pt_c), space.length(pt_a, pt_c)) return (bisector_lenth - euclidean_bisector_length)
def convert(source_dir: Path, dest_dir): dest_dir = Path(dest_dir) dest_dir.mkdir(exist_ok=True) opus_state = OpusState(source_dir) opus_state.tokenizer.save_pretrained(dest_dir) model = opus_state.load_marian_model() model = model.half() model.save_pretrained(dest_dir) model.from_pretrained(dest_dir)
def parity_to_cmd(node: Dict, datadir: str, chain_id: int, chain_spec: str, verbosity: str) -> Command: node_config = {'nodekeyhex': 'node-key', 'password': 'password', 'port': 'port', 'rpcport': 'jsonrpc-port', 'pruning-history': 'pruning-history', 'pruning': 'pruning', 'pruning-memory': 'pruning-memory', 'cache-size-db': 'cache-size-db', 'cache-size-blocks': 'cache-size-blocks', 'cache-size-queue': 'cache-size-queue', 'cache-size': 'cache-size', 'bootnodes': 'bootnodes'} cmd = ['openethereum'] for (config, option) in node_config.items(): if (config in node): cmd.append(f'--{option}={node[config]}') cmd.extend(['--jsonrpc-apis=eth,net,web3,parity,personal,traces', '--jsonrpc-interface=127.0.0.1', '--no-discovery', '--no-ws', '--no-ipc', '--min-gas-price=', f'--base-path={datadir}', f'--chain={chain_spec}', f'--network-id={chain_id}', f'--logging={verbosity}']) if node.get('mine', False): cmd.extend([f"--engine-signer={to_checksum_address(node['address'])}", '--force-sealing']) log.debug('parity command', command=cmd) return cmd
def processor_to_arch(): if (Processor.type == ProcessorType.PLFM_386): return (ArchX64 if (Processor.mode == ArchMode.MODE64) else ArchX86) elif (Processor.type == ProcessorType.PLFM_ARM): return (ArchARM64 if (Processor.mode == ArchMode.MODE64) else ArchARM) else: assert False
class Migration(migrations.Migration): dependencies = [('conditions', '0015_move_attribute_to_attributeentity'), ('projects', '0022_move_attribute_to_attributeentity'), ('tasks', '0012_move_attribute_to_attributeentity'), ('domain', '0036_remove_range_and_verbosename')] operations = [migrations.AddField(model_name='attribute', name='_', field=models.BooleanField(default=False)), migrations.RemoveField(model_name='attribute', name='attributeentity_ptr'), migrations.DeleteModel(name='Attribute')]
def diff_iloc(dfs, new, window=None): dfs = deque(dfs) if (len(new) > 0): dfs.append(new) old = [] if (len(dfs) > 0): n = (sum(map(len, dfs)) - window) while (n > 0): if (len(dfs[0]) <= n): df = dfs.popleft() old.append(df) n -= len(df) else: old.append(dfs[0].iloc[:n]) dfs[0] = dfs[0].iloc[n:] n = 0 return (dfs, old)
class GraphDataBetween(GraphData_Base): def draw(self, axis, figure=None): (x, y1, y2) = self.data axis.fill_between(x, y1, y2, **self.line_format) if ('label' in self.line_format): patch_color = {} patch_color.update(self.line_format) p = Rectangle((0, 0), 1, 1, **patch_color) return (p, self.line_format['label'])
class ModelPool(): def __init__(self, dic_path, dic_exp_conf): self.dic_path = dic_path self.exp_conf = dic_exp_conf self.num_best_model = self.exp_conf['NUM_BEST_MODEL'] if os.path.exists(os.path.join(self.dic_path['PATH_TO_WORK_DIRECTORY'], 'best_model.pkl')): self.best_model_pool = pickle.load(open(os.path.join(self.dic_path['PATH_TO_WORK_DIRECTORY'], 'best_model.pkl'), 'rb')) else: self.best_model_pool = [] def single_test(self, cnt_round): print('Start testing model pool') records_dir = self.dic_path['PATH_TO_WORK_DIRECTORY'] if_gui = False nan_thres = 80 dic_agent_conf = json.load(open(os.path.join(records_dir, 'agent.conf'), 'r')) dic_exp_conf = json.load(open(os.path.join(records_dir, 'exp.conf'), 'r')) dic_traffic_env_conf = json.load(open(os.path.join(records_dir, 'traffic_env.conf'), 'r')) run_cnt = dic_exp_conf['RUN_COUNTS'] dic_traffic_env_conf['IF_GUI'] = if_gui if os.path.exists(os.path.join(records_dir, 'test_exp.conf')): json.dump(dic_exp_conf, open(os.path.join(records_dir, 'test_exp.conf'), 'w')) if (dic_exp_conf['MODEL_NAME'] in dic_exp_conf['LIST_MODEL_NEED_TO_UPDATE']): dic_agent_conf['EPSILON'] = 0 dic_agent_conf['MIN_EPSILON'] = 0 agent_name = dic_exp_conf['MODEL_NAME'] agent = DIC_AGENTS[agent_name](dic_agent_conf=dic_agent_conf, dic_traffic_env_conf=dic_traffic_env_conf, dic_path=self.dic_path, cnt_round=0) if 1: agent.load_network('round_{0}'.format(cnt_round)) path_to_log = os.path.join(self.dic_path['PATH_TO_WORK_DIRECTORY'], 'test_round', 'round_{0}'.format(cnt_round)) if (not os.path.exists(path_to_log)): os.makedirs(path_to_log) env = DIC_ENVS[dic_traffic_env_conf['SIMULATOR_TYPE']](path_to_log=path_to_log, path_to_work_directory=self.dic_path['PATH_TO_WORK_DIRECTORY'], dic_traffic_env_conf=dic_traffic_env_conf) done = False state = env.reset() step_num = 0 while ((not done) and (step_num < int((dic_exp_conf['RUN_COUNTS'] / dic_traffic_env_conf['MIN_ACTION_TIME'])))): action_list = [] for one_state in state: action = agent.choose_action(step_num, one_state) action_list.append(action) (next_state, reward, done, _) = env.step(action_list) state = next_state step_num += 1 env.bulk_log() env.end_sumo() df_vehicle_inter_0 = pd.read_csv(os.path.join(path_to_log, 'vehicle_inter_0.csv'), sep=',', header=0, dtype={0: str, 1: float, 2: float}, names=['vehicle_id', 'enter_time', 'leave_time']) duration = (df_vehicle_inter_0['leave_time'].values - df_vehicle_inter_0['enter_time'].values) dur = np.mean([time for time in duration if (not isnan(time))]) real_traffic_vol = 0 nan_num = 0 for time in duration: if (not isnan(time)): real_traffic_vol += 1 else: nan_num += 1 traffic_vol = get_traffic_volume(dic_exp_conf['TRAFFIC_FILE'][0], run_cnt) print(nan_num, nan_thres, self.best_model_pool) if (nan_num < nan_thres): cnt = 0 for i in range(len(self.best_model_pool)): if (self.best_model_pool[i][1] > dur): break cnt += 1 self.best_model_pool.insert(cnt, [cnt_round, dur]) num_max = min(len(self.best_model_pool), self.exp_conf['NUM_BEST_MODEL']) self.best_model_pool = self.best_model_pool[:num_max] print(self.best_model_pool) f = open(os.path.join(self.dic_path['PATH_TO_WORK_DIRECTORY'], 'best_model_pool.log'), 'a') f.write(('round: %d ' % cnt_round)) for i in range(len(self.best_model_pool)): f.write(('id: %d, duration: %f, ' % (self.best_model_pool[i][0], self.best_model_pool[i][1]))) f.write('\n') f.close() print('model pool ends') def model_compare(self, cnt_round): print('Start testing model pool') records_dir = self.dic_path['PATH_TO_WORK_DIRECTORY'] if_gui = False nan_thres = 80 dic_agent_conf = json.load(open(os.path.join(records_dir, 'agent.conf'), 'r')) dic_exp_conf = json.load(open(os.path.join(records_dir, 'exp.conf'), 'r')) dic_sumo_env_conf = json.load(open(os.path.join(records_dir, 'sumo_env.conf'), 'r')) run_cnt = dic_exp_conf['RUN_COUNTS'] dic_sumo_env_conf['IF_GUI'] = if_gui if os.path.exists(os.path.join(records_dir, 'test_exp.conf')): json.dump(dic_exp_conf, open(os.path.join(records_dir, 'test_exp.conf'), 'w')) path_to_log = os.path.join(records_dir, 'test_round', ('round_%d' % cnt_round)) if 1: df_vehicle_inter_0 = pd.read_csv(os.path.join(path_to_log, 'vehicle_inter_0.csv'), sep=',', header=0, dtype={0: str, 1: float, 2: float}, names=['vehicle_id', 'enter_time', 'leave_time']) duration = (df_vehicle_inter_0['leave_time'].values - df_vehicle_inter_0['enter_time'].values) dur = np.mean([time for time in duration if (not isnan(time))]) real_traffic_vol = 0 nan_num = 0 for time in duration: if (not isnan(time)): real_traffic_vol += 1 else: nan_num += 1 traffic_vol = get_traffic_volume(dic_exp_conf['TRAFFIC_FILE'][0], run_cnt) print(nan_num, nan_thres, self.best_model_pool) if (nan_num < nan_thres): cnt = 0 for i in range(len(self.best_model_pool)): if (self.best_model_pool[i][1] > dur): break cnt += 1 self.best_model_pool.insert(cnt, [cnt_round, dur]) num_max = min(len(self.best_model_pool), self.exp_conf['NUM_BEST_MODEL']) self.best_model_pool = self.best_model_pool[:num_max] print(self.best_model_pool) f = open(os.path.join(self.dic_path['PATH_TO_WORK_DIRECTORY'], 'best_model_pool.log'), 'a') f.write(('round: %d ' % cnt_round)) for i in range(len(self.best_model_pool)): f.write(('id: %d, duration: %f, ' % (self.best_model_pool[i][0], self.best_model_pool[i][1]))) f.write('\n') f.close() print('model pool ends') def get(self): if (not self.best_model_pool): return else: ind = random.randint(0, (len(self.best_model_pool) - 1)) return self.best_model_pool[ind][0] def dump_model_pool(self): if self.best_model_pool: pickle.dump(self.best_model_pool, open(os.path.join(self.dic_path['PATH_TO_WORK_DIRECTORY'], 'best_model.pkl'), 'wb'))
def sync_perform(dispatcher, effect): successes = [] errors = [] effect = effect.on(success=successes.append, error=errors.append) perform(dispatcher, effect) if successes: return successes[0] elif errors: raise errors[0] else: raise NotSynchronousError(('Performing %r was not synchronous!' % (effect,)))
class LatticeModelResult(EigenstateResult): def __init__(self) -> None: super().__init__() self._algorithm_result: Optional[AlgorithmResult] = None self._computed_lattice_energies: Optional[np.ndarray] = None self._num_occupied_modals_per_mode: Optional[List[List[float]]] = None def algorithm_result(self) -> Optional[AlgorithmResult]: return self._algorithm_result _result.setter def algorithm_result(self, value: AlgorithmResult) -> None: self._algorithm_result = value def computed_lattice_energies(self) -> Optional[np.ndarray]: return self._computed_lattice_energies _lattice_energies.setter def computed_lattice_energies(self, value: np.ndarray) -> None: self._computed_lattice_energies = value def __str__(self) -> str: return '\n'.join(self._formatted()) def _formatted(self) -> List[str]: lines = [] lines.append('=== GROUND STATE ===') lines.append(' ') lines.append(f'* Lattice ground state energy : {np.round(self.computed_lattice_energies[0], self.formatting_precision)}') if ((self.computed_lattice_energies is not None) and (len(self.computed_lattice_energies) > 1)): lines.append(' ') lines.append('=== EXCITED STATES ===') lines.append(' ') for (idx, lattice_energy) in enumerate(self.computed_lattice_energies[1:]): lines.append(f'* {(idx + 1): 3d}: Lattice excited state energy: {np.round(lattice_energy, self.formatting_precision)}') return lines
class TrainOptions(BaseOptions): def initialize(self): BaseOptions.initialize(self) self._parser.add_argument('--print_freq_s', type=int, default=5, help='frequency of showing training results on console') self._parser.add_argument('--lr_policy', type=str, default='step', choices=['lambda', 'step', 'plateau']) self._parser.add_argument('--lr_decay_epochs', type=int, default=3, help="learning rate decays by 0.1 after every # epochs (lr_policy is 'step')") self._parser.add_argument('--teacher_nepochs', type=int, default=8, help='# of epochs to train') self._parser.add_argument('--student_nepochs', type=int, default=3, help='# of epochs for student to train') self._parser.add_argument('--n_students', type=int, default=5, help='# of students') self._parser.add_argument('--lr_F', type=float, default=0.0001, help='initial learning rate for G adam') self._parser.add_argument('--F_adam_b1', type=float, default=0.5, help='beta1 for G adam') self._parser.add_argument('--F_adam_b2', type=float, default=0.999, help='beta2 for G adam') self._parser.add_argument('--optimizer', type=str, default='Adam', choices=['Adam', 'SGD']) self.is_train = True
def test_plugin_dependencies_unmet(hatch, config_file, helpers, temp_dir, mock_plugin_installation): config_file.model.template.plugins['default']['tests'] = False config_file.save() project_name = 'My.App' with temp_dir.as_cwd(): result = hatch('new', project_name) assert (result.exit_code == 0), result.output project_path = (temp_dir / 'my-app') data_path = (temp_dir / 'data') data_path.mkdir() dependency = os.urandom(16).hex() (project_path / DEFAULT_CONFIG_FILE).write_text(helpers.dedent(f''' [env] requires = ["{dependency}"] ''')) project = Project(project_path) helpers.update_project_environment(project, 'default', {'skip-install': True, **project.config.envs['default']}) with project_path.as_cwd(env_vars={ConfigEnvVars.DATA: str(data_path)}): result = hatch('env', 'create') assert (result.exit_code == 0), result.output assert (result.output == helpers.dedent('\n Syncing environment plugin requirements\n Creating environment: default\n Checking dependencies\n ')) helpers.assert_plugin_installation(mock_plugin_installation, [dependency]) env_data_path = ((data_path / 'env') / 'virtual') assert env_data_path.is_dir() project_data_path = (env_data_path / project_path.name) assert project_data_path.is_dir() storage_dirs = list(project_data_path.iterdir()) assert (len(storage_dirs) == 1) storage_path = storage_dirs[0] assert (len(storage_path.name) == 8) env_dirs = list(storage_path.iterdir()) assert (len(env_dirs) == 1) env_path = env_dirs[0] assert (env_path.name == project_path.name)
class Leaf(Base): _prefix = '' lineno = 0 column = 0 def __init__(self, type, value, context=None, prefix=None, fixers_applied=[]): assert (0 <= type < 256), type if (context is not None): (self._prefix, (self.lineno, self.column)) = context self.type = type self.value = value if (prefix is not None): self._prefix = prefix self.fixers_applied = fixers_applied[:] def __repr__(self): return ('%s(%r, %r)' % (self.__class__.__name__, self.type, self.value)) def __unicode__(self): return (self.prefix + str(self.value)) if (sys.version_info > (3, 0)): __str__ = __unicode__ def _eq(self, other): return ((self.type, self.value) == (other.type, other.value)) def clone(self): return Leaf(self.type, self.value, (self.prefix, (self.lineno, self.column)), fixers_applied=self.fixers_applied) def leaves(self): (yield self) def post_order(self): (yield self) def pre_order(self): (yield self) def prefix(self): return self._prefix def prefix(self, prefix): self.changed() self._prefix = prefix
def looks_like_an_export(sexp): if (not isinstance(sexp, values.W_Cons)): return False if (sexp.car() is not export_sym): return False if (not isinstance(sexp.cdr(), values.W_Cons)): return False if (not isinstance(sexp.cdr().cdr(), values.W_Cons)): return False if (not isinstance(sexp.cdr().cdr().cdr(), values.W_Cons)): return False return True
class BCE_Loss(nn.Module): def __init__(self): super(BCE_Loss, self).__init__() self.loss = nn.BCEWithLogitsLoss(reduction='none') def forward(self, output, label): (output, label) = (output.view((- 1), 1), label.view((- 1), 1)) loss = self.loss(output, label.view((- 1), 1)) loss_pos = (loss[(label > 0.0)].sum().float() / label.gt(0.0).sum().float()) loss_neg = (loss[(label == 0.0)].sum().float() / (label.nelement() - label.gt(0.0).sum().float())) return (loss_pos.unsqueeze(0), loss_neg.unsqueeze(0))
def train(args, train_env, val_envs, aug_env=None, rank=(- 1)): default_gpu = is_default_gpu(args) if default_gpu: with open(os.path.join(args.log_dir, 'training_args.json'), 'w') as outf: json.dump(vars(args), outf, indent=4) writer = SummaryWriter(log_dir=args.log_dir) record_file = os.path.join(args.log_dir, 'train.txt') write_to_record_file((str(args) + '\n\n'), record_file) agent_class = Seq2SeqCMTAgent listener = agent_class(args, train_env, rank=rank) start_iter = 0 if (args.resume_file is not None): start_iter = listener.load(os.path.join(args.resume_file)) if default_gpu: write_to_record_file('\nLOAD the model from {}, iteration {}'.format(args.resume_file, start_iter), record_file) print(datetime.datetime.now()) if args.eval_first: loss_str = 'validation before training' for (env_name, (env, evaluator, name)) in val_envs.items(): if (name == 'val_train_seen'): continue listener.env = env listener.test(use_dropout=False, feedback='argmax', iters=None) preds = listener.get_results() preds = merge_dist_results(all_gather(preds)) if default_gpu: (score_summary, _, _) = env.eval_metrics(preds) loss_str += (', %s ' % env_name) for (metric, val) in score_summary.items(): loss_str += (', %s: %.2f' % (metric, val)) if default_gpu: write_to_record_file(loss_str, record_file) print('test language metric') for (env_name, (env, evaluator, name)) in val_envs.items(): if (name == 'val_train_seen'): continue listener.env = env path2inst = listener.valid_speaker() evaluator.evaluate(path2inst) eval_str = evaluator.eval.items() write_to_record_file(str(eval_str), record_file) print(datetime.datetime.now()) start = time.time() if default_gpu: write_to_record_file(('\nListener training starts, start iteration: %s' % str(start_iter)), record_file) if ((args.dataset == 'r4r') and (not args.r4r_testall)): best_val = {'val_unseen_sampled': {'spl': 0.0, 'sr': 0.0, 'state': ''}} else: best_val = {'val_unseen': {'spl': 0.0, 'sr': 0.0, 'state': ''}} for idx in range(start_iter, (start_iter + args.iters), args.log_every): listener.logs = defaultdict(list) interval = min(args.log_every, (args.iters - idx)) iter = (idx + interval) if (aug_env is None): task = args.task_name contrastive_loss = 0.0 caption_loss = 0.0 if (task == 'caption'): jdx_length = len(range((interval // 2))) for jdx in range((interval // 2)): listener.env = train_env caption_loss = listener.train_speaker(1) if default_gpu: print_progress(jdx, jdx_length, prefix='Progress:', suffix='Complete', bar_length=50) elif (task == 'vln'): jdx_length = len(range((interval // 2))) for jdx in range((interval // 2)): tasks = ['caption', 'regular'] weights = torch.Tensor([args.caption_task_weight, args.vln_task_weight]) task_id = torch.multinomial(weights, 1, replacement=True) if (task_id == 0): _task = 'caption' elif (task_id == 1): _task = 'regular' if (_task == 'caption'): listener.env = train_env caption_loss = listener.train_speaker(1) elif (_task == 'regular'): listener.env = train_env listener.train(1, feedback=args.feedback) if default_gpu: print_progress(jdx, jdx_length, prefix='Progress:', suffix='Complete', bar_length=50) else: contrastive_loss = 0.0 caption_loss = 0.0 jdx_length = len(range((interval // 2))) for jdx in range((interval // 2)): weights = torch.Tensor([args.caption_task_weight, args.vln_task_weight]) task_id = torch.multinomial(weights, 1, replacement=True) if (task_id == 0): task = 'caption' elif (task_id == 1): task = 'regular' if (task == 'caption'): listener.env = train_env caption_loss = listener.train_speaker(1) elif (task == 'contrastive'): listener.env = train_env contrastive_loss1 = listener.train_cont(1) listener.env = aug_env contrastive_loss2 = listener.train_cont(1) contrastive_loss = ((contrastive_loss1 + contrastive_loss2) / 2.0) else: listener.env = train_env listener.train(1, feedback=args.feedback) listener.env = aug_env listener.train(1, feedback=args.feedback) if default_gpu: print_progress(jdx, jdx_length, prefix='Progress:', suffix='Complete', bar_length=50) if default_gpu: total = max(sum(listener.logs['total']), 1) length = max(len(listener.logs['critic_loss']), 1) critic_loss = (sum(listener.logs['critic_loss']) / total) policy_loss = (sum(listener.logs['policy_loss']) / total) RL_loss = (sum(listener.logs['RL_loss']) / max(len(listener.logs['RL_loss']), 1)) IL_loss = (sum(listener.logs['IL_loss']) / max(len(listener.logs['IL_loss']), 1)) GP_loss = (sum(listener.logs['GP_loss']) / max(len(listener.logs['GP_loss']), 1)) entropy = (sum(listener.logs['entropy']) / total) writer.add_scalar('loss/critic', critic_loss, idx) writer.add_scalar('policy_entropy', entropy, idx) writer.add_scalar('loss/RL_loss', RL_loss, idx) writer.add_scalar('loss/IL_loss', IL_loss, idx) writer.add_scalar('loss/GP_loss', GP_loss, idx) writer.add_scalar('total_actions', total, idx) writer.add_scalar('max_length', length, idx) write_to_record_file(('\ntotal_actions %d, max_length %d, entropy %.4f, IL_loss %.4f, RL_loss %.4f, GP_loss %.4f, policy_loss %.4f, critic_loss %.4f, caption_loss %.4f, contrastive_loss %.4f' % (total, length, entropy, IL_loss, RL_loss, GP_loss, policy_loss, critic_loss, caption_loss, contrastive_loss)), record_file) if (args.task_name == 'caption'): print('test language metric') for (env_name, (env, evaluator, name)) in val_envs.items(): if (name == 'val_train_seen'): continue listener.env = env path2inst = listener.valid_speaker() evaluator.evaluate(path2inst) eval_str = evaluator.eval.items() write_to_record_file(str(eval_str), record_file) continue loss_str = 'iter {}'.format(iter) for (env_name, (env, evaluator, name)) in val_envs.items(): if ((name == 'val_train_seen') or (name == 'val_seen')): continue listener.env = env listener.test(use_dropout=False, feedback='argmax', iters=None) preds = listener.get_results() preds = merge_dist_results(all_gather(preds)) if default_gpu: (score_summary, _, _) = env.eval_metrics(preds) loss_str += ('\n %18s ' % env_name) for (metric, val) in score_summary.items(): loss_str += (', %s: %.2f' % (metric, val)) writer.add_scalar(('%s/%s' % (metric, env_name)), score_summary[metric], idx) if (env_name in best_val): if ((score_summary['sr'] + score_summary['spl']) > (best_val[env_name]['spl'] + best_val[env_name]['sr'])): best_val[env_name]['spl'] = score_summary['spl'] best_val[env_name]['sr'] = score_summary['sr'] best_val[env_name]['state'] = ('Iter %d %s' % (iter, loss_str)) listener.save(idx, os.path.join(args.ckpt_dir, ('best_%s' % env_name))) if (args.multiple_saving and (score_summary['sr'] > args.baseline_sr)): listener.save(idx, os.path.join(args.ckpt_dir, ('best_%s_%s' % (env_name, iter)))) if default_gpu: listener.save(idx, os.path.join(args.ckpt_dir, 'latest_dict')) write_to_record_file(('%s (%d %d%%) %s' % (timeSince(start, (float(iter) / args.iters)), iter, ((float(iter) / args.iters) * 100), loss_str)), record_file) write_to_record_file('BEST RESULT TILL NOW', record_file) for env_name in best_val: write_to_record_file(((env_name + ' | ') + best_val[env_name]['state']), record_file)
def _get_boolability_no_mvv(value: Value) -> Boolability: if isinstance(value, AnnotatedValue): value = value.value value = replace_known_sequence_value(value) if isinstance(value, AnyValue): return Boolability.boolable elif isinstance(value, UnboundMethodValue): if value.secondary_attr_name: return Boolability.boolable else: return Boolability.type_always_true elif isinstance(value, TypedDictValue): if value.num_required_keys(): return Boolability.type_always_true else: return Boolability.boolable elif isinstance(value, SequenceValue): if (not value.members): if (value.typ is tuple): return Boolability.value_always_false else: return Boolability.value_always_false_mutable may_be_empty = all((is_many for (is_many, _) in value.members)) if may_be_empty: return Boolability.boolable if (value.typ is tuple): return Boolability.type_always_true else: return Boolability.value_always_true_mutable elif isinstance(value, DictIncompleteValue): if any(((pair.is_required and (not pair.is_many)) for pair in value.kv_pairs)): return Boolability.value_always_true_mutable elif value.kv_pairs: return Boolability.boolable else: return Boolability.value_always_false_mutable elif isinstance(value, SubclassValue): return Boolability.type_always_true elif isinstance(value, KnownValue): try: boolean_value = bool(value.val) except Exception: return Boolability.erroring_bool if isinstance(value.val, KNOWN_MUTABLE_TYPES): if boolean_value: return Boolability.value_always_true_mutable else: return Boolability.value_always_false_mutable type_boolability = _get_type_boolability(type(value.val), is_exact=True) if boolean_value: if (type_boolability is Boolability.boolable): return Boolability.value_always_true elif (type_boolability is Boolability.type_always_true): return Boolability.type_always_true else: assert False, f'inconsistent boolabilities: {boolean_value}, {type_boolability}, {value!r}' elif (type_boolability is Boolability.boolable): return Boolability.value_always_false else: assert False, f'inconsistent boolabilities: {boolean_value}, {type_boolability}, {value!r}' elif isinstance(value, TypedValue): if isinstance(value.typ, str): return Boolability.boolable return _get_type_boolability(value.typ) else: assert False, f'unhandled value {value!r}'
_fixtures(WebFixture) def test_reading_cookies_on_initialising_a_session(web_fixture): fixture = web_fixture UserSession.initialise_web_session_on(fixture.context) assert (not fixture.context.session.is_active()) assert (not fixture.context.session.is_secured()) fixture.context.session = None user_session = UserSession() user_session.set_last_activity_time() Session.add(user_session) fixture.request.headers['Cookie'] = ('reahl=%s' % user_session.as_key()) UserSession.initialise_web_session_on(fixture.context) assert (fixture.context.session is user_session) assert fixture.context.session.is_active() assert (not fixture.context.session.is_secured()) fixture.request.scheme = ' fixture.context.session = None user_session = UserSession() user_session.set_last_activity_time() Session.add(user_session) fixture.request.headers['Cookie'] = ('reahl=%s , reahl_secure=%s' % (user_session.as_key(), user_session.secure_salt)) UserSession.initialise_web_session_on(fixture.context) assert (fixture.context.session is user_session) assert fixture.context.session.is_active() assert fixture.context.session.is_secured() fixture.request.scheme = ' fixture.context.session = None user_session = UserSession() user_session.set_last_activity_time() Session.add(user_session) fixture.request.headers['Cookie'] = ('reahl=%s , reahl_secure=%s' % (user_session.as_key(), user_session.secure_salt)) UserSession.initialise_web_session_on(fixture.context) assert (fixture.context.session is user_session) assert fixture.context.session.is_active() assert (not fixture.context.session.is_secured())
def save_as_tf_module_multi_gpu(loading_path: 'str', saving_path: 'str', compressed_ops: List['str'], input_shape: Tuple): def trace_model(inputs): tf.keras.backend.set_learning_phase(1) model = load_tf_sess_variables_to_keras_single_gpu(loading_path, compressed_ops) train_out = model(inputs, training=True) return train_out def export(): tf.keras.backend.clear_session() with tf.compat.v1.keras.backend.get_session() as sess: fn = tf.wrap_function(trace_model, signature=[tf.TensorSpec((None, input_shape[0], input_shape[1], input_shape[2]), tf.float32)]) train_fn = fn.prune(feeds=fn.inputs[0], fetches=fn.outputs[0]) obj = tf.Module() obj.variables_list = list(fn.graph.variables) sess.run(tf.compat.v1.global_variables_initializer()) tf.saved_model.save(obj, saving_path, {'train': train_fn, 'serving_default': train_fn}) export()
def convert(src, dst): regnet_model = torch.load(src) blobs = regnet_model['model_state'] state_dict = OrderedDict() converted_names = set() for (key, weight) in blobs.items(): if ('stem' in key): convert_stem(key, weight, state_dict, converted_names) elif ('head' in key): convert_head(key, weight, state_dict, converted_names) elif key.startswith('s'): convert_reslayer(key, weight, state_dict, converted_names) for key in blobs: if (key not in converted_names): print(f'not converted: {key}') checkpoint = dict() checkpoint['state_dict'] = state_dict torch.save(checkpoint, dst)
def test_run_pyscript_py_locals(base_app, request): test_dir = os.path.dirname(request.module.__file__) python_script = os.path.join(test_dir, 'pyscript', 'py_locals.py') base_app.py_locals['test_var'] = 5 base_app.py_locals['my_list'] = [] run_cmd(base_app, 'run_pyscript {}'.format(python_script)) assert (base_app.py_locals['test_var'] == 5) assert (base_app.py_locals['my_list'][0] == 2)
def test_plural_within_rules(): p = plural.PluralRule({'one': 'n is 1', 'few': 'n within 2,4,7..9'}) assert (repr(p) == "<PluralRule 'one: n is 1, few: n within 2,4,7..9'>") assert (plural.to_javascript(p) == "(function(n) { return ((n == 2) || (n == 4) || (n >= 7 && n <= 9)) ? 'few' : (n == 1) ? 'one' : 'other'; })") assert (plural.to_gettext(p) == 'nplurals=3; plural=(((n == 2) || (n == 4) || (n >= 7 && n <= 9)) ? 1 : (n == 1) ? 0 : 2);') assert (p(0) == 'other') assert (p(1) == 'one') assert (p(2) == 'few') assert (p(3) == 'other') assert (p(4) == 'few') assert (p(5) == 'other') assert (p(6) == 'other') assert (p(7) == 'few') assert (p(8) == 'few') assert (p(9) == 'few')
def _git_str() -> Optional[str]: commit = None if (not hasattr(sys, 'frozen')): try: gitpath = os.path.join(os.path.dirname(os.path.realpath(__file__)), os.path.pardir, os.path.pardir) except (NameError, OSError): log.misc.exception('Error while getting git path') else: commit = _git_str_subprocess(gitpath) if (commit is not None): return commit try: return resources.read_file('git-commit-id') except (OSError, ImportError): return None
def _get_jk_kshift(mf, dm_kpts, hermi, kpts, kshift, with_j=True, with_k=True): from pyscf.pbc.df.df_jk import get_j_kpts_kshift, get_k_kpts_kshift vj = vk = None if with_j: vj = get_j_kpts_kshift(mf.with_df, dm_kpts, kshift, hermi=hermi, kpts=kpts) if with_k: vk = get_k_kpts_kshift(mf.with_df, dm_kpts, kshift, hermi=hermi, kpts=kpts, exxdiv=mf.exxdiv) return (vj, vk)
def test_PVSystem_get_ac_pvwatts_multi(pvwatts_system_defaults, pvwatts_system_kwargs, mocker): mocker.spy(inverter, 'pvwatts_multi') expected = [pd.Series([0.0, 48.123524, 86.4]), pd.Series([0.0, 45.89355, 85.5])] systems = [pvwatts_system_defaults, pvwatts_system_kwargs] for (base_sys, exp) in zip(systems, expected): system = pvsystem.PVSystem(arrays=[pvsystem.Array(pvsystem.FixedMount(0, 180)), pvsystem.Array(pvsystem.FixedMount(0, 180))], inverter_parameters=base_sys.inverter_parameters) pdcs = pd.Series([0.0, 25.0, 50.0]) pacs = system.get_ac('pvwatts', (pdcs, pdcs)) assert_series_equal(pacs, exp) assert (inverter.pvwatts_multi.call_count == 2) with pytest.raises(ValueError, match='Length mismatch for per-array parameter'): system.get_ac('pvwatts', (pdcs,)) with pytest.raises(ValueError, match='Length mismatch for per-array parameter'): system.get_ac('pvwatts', pdcs) with pytest.raises(ValueError, match='Length mismatch for per-array parameter'): system.get_ac('pvwatts', (pdcs, pdcs, pdcs))
class Encoder(nn.Module): def __init__(self, in_channels, num_classes): super().__init__() self.initial_block = DownsamplerBlock(in_channels, 16) self.layers = nn.ModuleList() self.layers.append(DownsamplerBlock(16, 64)) for x in range(0, 5): self.layers.append(non_bottleneck_1d(64, 0.03, 1)) self.layers.append(DownsamplerBlock(64, 128)) for x in range(0, 2): self.layers.append(non_bottleneck_1d(128, 0.3, 2)) self.layers.append(non_bottleneck_1d(128, 0.3, 4)) self.layers.append(non_bottleneck_1d(128, 0.3, 8)) self.layers.append(non_bottleneck_1d(128, 0.3, 16)) self.output_conv = nn.Conv2d(128, num_classes, 1, stride=1, padding=0, bias=True) def forward(self, input, predict=False): output = self.initial_block(input) for layer in self.layers: output = layer(output) if predict: output = self.output_conv(output) return output
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments)) if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')): (model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: (model_args, data_args, training_args) = parser.parse_args_into_dataclasses() data_args.output_dir = training_args.output_dir real_name_or_path = model_args.model_name_or_path data_args.model_name_or_path = model_args.model_name_or_path data_args.tokenizer_name_or_path = model_args.model_name_or_path training_args.cl_temperature = data_args.cl_temperature training_args.remove_unused_columns = False if (not os.path.isdir(data_args.output_dir)): os.makedirs(data_args.output_dir, exist_ok=True) logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', handlers=[logging.StreamHandler(sys.stdout)]) log_level = logging.ERROR logger.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() last_checkpoint = None if (os.path.isdir(training_args.output_dir) and training_args.do_train and (not training_args.overwrite_output_dir)): last_checkpoint = get_last_checkpoint(training_args.output_dir) if ((last_checkpoint is None) and (len(os.listdir(training_args.output_dir)) > 0)): raise ValueError(f'Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome.') elif ((last_checkpoint is not None) and (training_args.resume_from_checkpoint is None)): logger.info(f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change the `--output_dir` or add `--overwrite_output_dir` to train from scratch.') tokenizer = AutoTokenizer.from_pretrained((model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path), cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer, revision=model_args.model_revision, use_auth_token=(True if model_args.use_auth_token else None)) set_seed(training_args.seed) with open(os.path.join(model_args.cache_dir, 'medi-data.json')) as f: train_examples_raw = json.load(f) if data_args.debug_mode: train_examples_raw = train_examples_raw[:data_args.debug_mode] old_train_examples_raw = train_examples_raw total_train_n = len(old_train_examples_raw) real_batch_size = max(training_args.per_device_train_batch_size, (training_args.per_device_train_batch_size * torch.cuda.device_count())) def get_examples_raw(old_examples_raw, total_n, real_batch_size): examples_raw = [] for idx in range(0, total_n, real_batch_size): local_task_name = old_examples_raw[idx]['task_id'] cur_batch = [] include_batch = True for idx1 in range(idx, min((idx + real_batch_size), total_n)): if (not (old_examples_raw[idx1]['task_id'] == local_task_name)): print(f"one batch in task {old_examples_raw[idx1]['task_id']} is skipped") include_batch = False break else: cur_batch.append(old_examples_raw[idx1]) if (include_batch and (len(cur_batch) == real_batch_size)): examples_raw.append(cur_batch) return examples_raw train_examples_raw = get_examples_raw(old_train_examples_raw, total_train_n, real_batch_size) random.shuffle(train_examples_raw) if ((data_args.max_examples is not None) and (len((train_examples_raw * real_batch_size)) > data_args.max_examples)): train_examples_raw = train_examples_raw[:int((data_args.max_examples / real_batch_size))] train_examples_raw_batch = train_examples_raw train_examples_raw = [] for b in train_examples_raw_batch: train_examples_raw += b print(f'There are {len(train_examples_raw)} pairs to train in total.') if data_args.debug_mode: train_examples_raw = train_examples_raw[:int(data_args.debug_mode)] def get_dataset(examples_raw): examples = {'query': [], 'pos': [], 'neg': [], 'task_id': []} task_name_map = {} total_num = len(examples_raw) task_count = 0 for i in range(total_num): cur_e = examples_raw[i] for k in ['query', 'pos', 'neg']: for s in cur_e[k][:(- 1)]: assert (not ('!#$%^&**!#$%^&**' in s)) cur_e[k][(- 1)] = str(cur_e[k][(- 1)]) if (not data_args.add_prompt_to_document): cur_e[k][0] = '' assert (cur_e[k][0].startswith('Represent ') or (cur_e[k][0] == '')) examples[k].append('!#$%^&**!#$%^&**'.join(cur_e[k])) if (not (cur_e['task_id'] in task_name_map)): task_name_map[cur_e['task_id']] = task_count task_count += 1 examples['task_id'].append(task_name_map[cur_e['task_id']]) return examples train_raw_datasets = DatasetDict({'train': Dataset.from_dict(get_dataset(train_examples_raw))}) model = INSTRUCTOR(real_name_or_path, cache_folder=model_args.cache_dir) column_names = train_raw_datasets['train'].column_names def preprocess_function(examples): all_tokenized = None for key in ['query', 'pos', 'neg']: num = len(examples[key]) contexts = [] concatenated_input_texts = [] for local_idx in range(num): splits = examples[key][local_idx].split('!#$%^&**!#$%^&**') assert (len(splits) == 2) contexts.append(splits[0]) concatenated_input_texts.append(''.join(splits)) assert isinstance(contexts[(- 1)], str) assert isinstance(concatenated_input_texts[(- 1)], str) tokenized = tokenizer(concatenated_input_texts, padding='max_length', truncation='longest_first', return_tensors='pt', max_length=data_args.max_source_length) context_tok = tokenizer(contexts, padding='max_length', truncation='longest_first', return_tensors='pt', max_length=data_args.max_source_length) tokenized['context_masks'] = torch.sum(context_tok['attention_mask'], dim=1) tokenized['context_masks'] = (tokenized['context_masks'] - 1) for my_idx in range(len(tokenized['context_masks'])): if (tokenized['context_masks'][my_idx] <= 1): tokenized['context_masks'][my_idx] = 0 keys = tokenized.keys() if (all_tokenized is None): all_tokenized = tokenized.copy() for k in keys: all_tokenized[k] = all_tokenized[k].tolist() for k in keys: all_tokenized[f'{key}_{k}'] = tokenized[k].tolist() all_tokenized['task_id'] = examples['task_id'] return all_tokenized train_dataset = train_raw_datasets['train'] val_dataset = None if data_args.validation_file: with open(data_args.validation_file) as f: val_examples_raw = json.load(f) old_val_examples_raw = val_examples_raw total_val_n = len(old_val_examples_raw) val_examples_raw = get_examples_raw(old_val_examples_raw, total_val_n, real_batch_size) random.shuffle(val_examples_raw) val_examples_raw_batch = val_examples_raw val_examples_raw = [] for b in val_examples_raw_batch: val_examples_raw += b print(f'There are {len(val_examples_raw)} pairs in val dataset.') val_raw_datasets = DatasetDict({'val': Dataset.from_dict(get_dataset(val_examples_raw))}) val_dataset = val_raw_datasets['val'] with training_args.main_process_first(desc='validation dataset map pre-processing'): val_dataset = val_dataset.map(preprocess_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=(not data_args.overwrite_cache), desc='Running tokenizer on val dataset') if (data_args.max_train_samples is not None): max_train_samples = min(len(train_dataset), data_args.max_train_samples) train_dataset = train_dataset.select(range(max_train_samples)) with training_args.main_process_first(desc='train dataset map pre-processing'): train_dataset = train_dataset.map(preprocess_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=(not data_args.overwrite_cache), desc='Running tokenizer on train dataset') label_pad_token_id = ((- 100) if data_args.ignore_pad_token_for_loss else tokenizer.pad_token_id) data_collator = DataCollatorForSeq2Seq(tokenizer, model=model, label_pad_token_id=label_pad_token_id, pad_to_multiple_of=(8 if training_args.fp16 else None)) trainer = InstructorTrainer(model=model, args=training_args, train_dataset=train_dataset, eval_dataset=val_dataset, tokenizer=tokenizer, data_collator=data_collator, compute_metrics=None) checkpoint = None if (training_args.resume_from_checkpoint is not None): checkpoint = training_args.resume_from_checkpoint elif (last_checkpoint is not None): checkpoint = last_checkpoint trainer.train(resume_from_checkpoint=checkpoint) trainer.model.save(training_args.output_dir)
class PyTorchDiscriminator(DiscriminativeNetwork): def __init__(self, n_features: int=1, n_out: int=1) -> None: super().__init__() if (not _HAS_TORCH): raise MissingOptionalLibraryError(libname='Pytorch', name='PyTorchDiscriminator', pip_install="pip install 'qiskit-aqua[torch]'") self._n_features = n_features self._n_out = n_out from ._pytorch_discriminator_net import DiscriminatorNet self._discriminator = DiscriminatorNet(self._n_features, self._n_out) self._optimizer = optim.Adam(self._discriminator.parameters(), lr=1e-05, amsgrad=True) self._ret = {} def set_seed(self, seed: int): torch.manual_seed(seed) def save_model(self, snapshot_dir: str): torch.save(self._discriminator, os.path.join(snapshot_dir, 'discriminator.pt')) def load_model(self, load_dir: str): self._discriminator = torch.load(load_dir) def discriminator_net(self): return self._discriminator _net.setter def discriminator_net(self, net): self._discriminator = net def get_label(self, x, detach=False): if isinstance(x, torch.Tensor): pass else: x = torch.tensor(x, dtype=torch.float32) x = Variable(x) if detach: return self._discriminator.forward(x).detach().numpy() else: return self._discriminator.forward(x) def loss(self, x, y, weights=None): if (weights is not None): loss_funct = nn.BCELoss(weight=weights, reduction='sum') else: loss_funct = nn.BCELoss() return loss_funct(x, y) def gradient_penalty(self, x, lambda_=5.0, k=0.01, c=1.0): if isinstance(x, torch.Tensor): pass else: x = torch.tensor(x, dtype=torch.float32) x = Variable(x) delta_ = (torch.rand(x.size()) * c) z = Variable((x + delta_), requires_grad=True) o_l = self.get_label(z) d_g = torch.autograd.grad(o_l, z, grad_outputs=torch.ones(o_l.size()), create_graph=True)[0].view(z.size(0), (- 1)) return (lambda_ * ((d_g.norm(p=2, dim=1) - k) ** 2).mean()) def train(self, data: Iterable, weights: Iterable, penalty: bool=False, quantum_instance: Optional[QuantumInstance]=None, shots: Optional[int]=None) -> Dict[(str, Any)]: self._optimizer.zero_grad() real_batch = cast(Sequence, data)[0] real_prob = cast(Sequence, weights)[0] generated_batch = cast(Sequence, data)[1] generated_prob = cast(Sequence, weights)[1] real_batch = np.reshape(real_batch, (len(real_batch), self._n_features)) real_batch = torch.tensor(real_batch, dtype=torch.float32) real_batch = Variable(real_batch) real_prob = np.reshape(real_prob, (len(real_prob), 1)) real_prob = torch.tensor(real_prob, dtype=torch.float32) prediction_real = self.get_label(real_batch) error_real = self.loss(prediction_real, torch.ones(len(prediction_real), 1), real_prob) error_real.backward() generated_batch = np.reshape(generated_batch, (len(generated_batch), self._n_features)) generated_prob = np.reshape(generated_prob, (len(generated_prob), 1)) generated_prob = torch.tensor(generated_prob, dtype=torch.float32) prediction_fake = self.get_label(generated_batch) error_fake = self.loss(prediction_fake, torch.zeros(len(prediction_fake), 1), generated_prob) error_fake.backward() if penalty: self.gradient_penalty(real_batch).backward() self._optimizer.step() loss_ret = (0.5 * (error_real + error_fake)) self._ret['loss'] = loss_ret.detach().numpy() params = [] for param in self._discriminator.parameters(): params.append(param.data.detach().numpy()) self._ret['params'] = params return self._ret
class DOCIHamiltonianTest(unittest.TestCase): def setUp(self): self.geometry = [('H', (0.0, 0.0, 0.0)), ('H', (0.0, 0.0, 0.7414))] self.basis = 'sto-3g' self.multiplicity = 1 self.filename = os.path.join(DATA_DIRECTORY, 'H2_sto-3g_singlet_0.7414') self.molecule = MolecularData(self.geometry, self.basis, self.multiplicity, filename=self.filename) self.molecule.load() def test_n_body_tensor_errors(self): doci_hamiltonian = DOCIHamiltonian.zero(n_qubits=2) with self.assertRaises(TypeError): doci_hamiltonian.n_body_tensors = 0 with self.assertRaises(IndexError): _ = doci_hamiltonian[((0, 0), (0, 0))] with self.assertRaises(IndexError): _ = doci_hamiltonian[((0, 0), (0, 0), (0, 0), (0, 0))] with self.assertRaises(IndexError): _ = doci_hamiltonian[((1, 1), (0, 0))] with self.assertRaises(IndexError): _ = doci_hamiltonian[((0, 1), (2, 1), (3, 0), (8, 0))] def test_errors_operations(self): doci_hamiltonian = DOCIHamiltonian.zero(n_qubits=2) doci_hamiltonian2 = DOCIHamiltonian.zero(n_qubits=3) with self.assertRaises(TypeError): doci_hamiltonian += 'a' with self.assertRaises(TypeError): doci_hamiltonian -= 'a' with self.assertRaises(TypeError): doci_hamiltonian *= 'a' with self.assertRaises(TypeError): doci_hamiltonian /= 'a' with self.assertRaises(TypeError): doci_hamiltonian += doci_hamiltonian2 with self.assertRaises(TypeError): doci_hamiltonian -= doci_hamiltonian2 def test_adding_constants(self): doci_hamiltonian = DOCIHamiltonian.zero(n_qubits=2) doci_hamiltonian += 2 self.assertAlmostEqual(doci_hamiltonian.constant, 2) doci_hamiltonian -= 3 self.assertAlmostEqual(doci_hamiltonian.constant, (- 1)) def test_basic_operations(self): doci_hamiltonian1 = DOCIHamiltonian.zero(n_qubits=2) doci_hamiltonian2 = DOCIHamiltonian.from_integrals(constant=self.molecule.nuclear_repulsion, one_body_integrals=self.molecule.one_body_integrals, two_body_integrals=self.molecule.two_body_integrals) self.assertTrue((doci_hamiltonian2 == (doci_hamiltonian1 + doci_hamiltonian2))) self.assertTrue(((doci_hamiltonian1 - doci_hamiltonian2) == (doci_hamiltonian2 / (- 1)))) self.assertTrue(((doci_hamiltonian2 * 0) == doci_hamiltonian1)) def test_error(self): doci_hamiltonian = DOCIHamiltonian.from_integrals(constant=self.molecule.nuclear_repulsion, one_body_integrals=self.molecule.one_body_integrals, two_body_integrals=self.molecule.two_body_integrals) with self.assertRaises(TypeError): doci_hamiltonian[((1, 0), (0, 1))] = 1 with self.assertRaises(IndexError): _ = doci_hamiltonian[((1, 0),)] with self.assertRaises(IndexError): _ = doci_hamiltonian[((1, 1), (0, 0))] with self.assertRaises(IndexError): _ = doci_hamiltonian[((0, 1), (1, 1), (0, 0), (2, 0))] def test_getting_setting_constant(self): doci_hamiltonian = DOCIHamiltonian.zero(n_qubits=2) doci_hamiltonian.constant = 1 self.assertEqual(doci_hamiltonian[()], 1) def test_getting_setting_1body(self): doci_hamiltonian = DOCIHamiltonian.zero(n_qubits=2) doci_hamiltonian.hc[0] = 2 doci_hamiltonian.hc[1] = 4 self.assertEqual(doci_hamiltonian[((0, 1), (0, 0))], 1) self.assertEqual(doci_hamiltonian[((1, 1), (1, 0))], 1) self.assertEqual(doci_hamiltonian[((2, 1), (2, 0))], 2) self.assertEqual(doci_hamiltonian[((3, 1), (3, 0))], 2) def test_getting_setting_hr2(self): doci_hamiltonian = DOCIHamiltonian.zero(n_qubits=2) doci_hamiltonian.hr2[(0, 0)] = 2 doci_hamiltonian.hr2[(1, 1)] = 4 self.assertEqual(doci_hamiltonian[((0, 1), (1, 1), (1, 0), (0, 0))], 1) self.assertEqual(doci_hamiltonian[((1, 1), (0, 1), (0, 0), (1, 0))], 1) self.assertEqual(doci_hamiltonian[((2, 1), (3, 1), (3, 0), (2, 0))], 2) self.assertEqual(doci_hamiltonian[((3, 1), (2, 1), (2, 0), (3, 0))], 2) doci_hamiltonian.hr2[(0, 1)] = 2 self.assertEqual(doci_hamiltonian[((0, 1), (2, 1), (2, 0), (0, 0))], 1) self.assertEqual(doci_hamiltonian[((0, 1), (3, 1), (3, 0), (0, 0))], 1) self.assertEqual(doci_hamiltonian[((1, 1), (2, 1), (2, 0), (1, 0))], 1) self.assertEqual(doci_hamiltonian[((1, 1), (3, 1), (3, 0), (1, 0))], 1) def test_getting_setting_hr1(self): doci_hamiltonian = DOCIHamiltonian.zero(n_qubits=2) doci_hamiltonian.hr1[(0, 1)] = 2 self.assertEqual(doci_hamiltonian[((0, 1), (1, 1), (3, 0), (2, 0))], 1) self.assertEqual(doci_hamiltonian[((1, 1), (0, 1), (2, 0), (3, 0))], 1) def test_from_integrals_to_qubit(self): hamiltonian = jordan_wigner(self.molecule.get_molecular_hamiltonian()) doci_hamiltonian = DOCIHamiltonian.from_integrals(constant=self.molecule.nuclear_repulsion, one_body_integrals=self.molecule.one_body_integrals, two_body_integrals=self.molecule.two_body_integrals).qubit_operator hamiltonian_matrix = get_sparse_operator(hamiltonian).toarray() doci_hamiltonian_matrix = get_sparse_operator(doci_hamiltonian).toarray() diagonal = numpy.real(numpy.diag(hamiltonian_matrix)) doci_diagonal = numpy.real(numpy.diag(doci_hamiltonian_matrix)) position_of_doci_diag_in_h = ([0] * len(doci_diagonal)) for (idx, doci_eigval) in enumerate(doci_diagonal): closest_in_diagonal = None for (idx2, eig) in enumerate(diagonal): if ((closest_in_diagonal is None) or (abs((eig - doci_eigval)) < abs((closest_in_diagonal - doci_eigval)))): closest_in_diagonal = eig position_of_doci_diag_in_h[idx] = idx2 assert (abs((closest_in_diagonal - doci_eigval)) < EQ_TOLERANCE), ((((('Value ' + str(doci_eigval)) + ' of the DOCI Hamiltonian ') + 'diagonal did not appear in the diagonal of the full ') + 'Hamiltonian. The closest value was ') + str(closest_in_diagonal)) sub_matrix = hamiltonian_matrix[numpy.ix_(position_of_doci_diag_in_h, position_of_doci_diag_in_h)] assert numpy.allclose(doci_hamiltonian_matrix, sub_matrix), (((((('The coupling between the DOCI states in the DOCI Hamiltonian ' + 'should be identical to that between these states in the full ') + 'Hamiltonian but the DOCI hamiltonian matrix\n') + str(doci_hamiltonian_matrix)) + '\ndoes not match the corresponding sub-matrix of the full ') + 'Hamiltonian\n') + str(sub_matrix))
def test_1epoch(class_limit=None, n_snip=5, opt_flow_len=10, image_shape=(224, 224), original_image_shape=(341, 256), batch_size=16, saved_weights=None): print(('\nValidating for weights: %s\n' % saved_weights)) data = DataSet(class_limit, image_shape, original_image_shape, n_snip, opt_flow_len, batch_size) val_generator = data.validation_generator() steps = data.n_batch spatial_cnn = ResearchModels(nb_classes=len(data.classes), n_snip=n_snip, opt_flow_len=opt_flow_len, image_shape=image_shape, saved_weights=saved_weights) spatial_cnn.model.fit_generator(generator=val_generator, steps_per_epoch=steps, max_queue_size=1) print('Finished validation of weights:', saved_weights)
def forward(apps: Apps, schema_editor: BaseDatabaseSchemaEditor) -> None: filter_: pydis_site.apps.api.models.Filter = apps.get_model('api', 'Filter') filter_list: pydis_site.apps.api.models.FilterList = apps.get_model('api', 'FilterList') filter_list_old = apps.get_model('api', 'FilterListOld') for (name, type_) in OLD_LIST_NAMES: objects = filter_list_old.objects.filter(type=name, allowed=type_) if (name == 'DOMAIN_NAME'): dm_content = 'Your message has been removed because it contained a blocked domain: `{domain}`.' elif (name == 'GUILD_INVITE'): dm_content = 'Per Rule 6, your invite link has been removed. Our server rules can be found here: else: dm_content = '' list_ = filter_list.objects.create(name=change_map[name], list_type=int(type_), guild_pings=(['Moderators'] if (name != 'FILE_FORMAT') else []), filter_dm=True, dm_pings=[], remove_context=(True if (name != 'FILTER_TOKEN') else False), bypass_roles=['Helpers'], enabled=True, dm_content=dm_content, dm_embed=('' if (name != 'FILE_FORMAT') else '*Defined at runtime.*'), infraction_type='NONE', infraction_reason='', infraction_duration=timedelta(seconds=0), infraction_channel=0, disabled_channels=[], disabled_categories=(['CODE JAM'] if (name in ('FILE_FORMAT', 'GUILD_INVITE')) else []), enabled_channels=[], enabled_categories=[], send_alert=(name in ('GUILD_INVITE', 'DOMAIN_NAME', 'FILTER_TOKEN'))) for object_ in objects: new_object = filter_.objects.create(content=object_.content, created_at=object_.created_at, updated_at=object_.updated_at, filter_list=list_, description=object_.comment, additional_settings={}, guild_pings=None, filter_dm=None, dm_pings=None, remove_context=None, bypass_roles=None, enabled=None, dm_content=None, dm_embed=None, infraction_type=None, infraction_reason=None, infraction_duration=None, infraction_channel=None, disabled_channels=None, disabled_categories=None, enabled_channels=None, enabled_categories=None, send_alert=None) new_object.save()
class Trainer(object): def __init__(self, device, dicts, opt, constants=None, setup_optimizer=True): self.device = device opt.node_rank = 0 opt.nodes = 1 self.world_size = len(opt.gpus) self.constants = (dill.loads(constants) if (constants is not None) else None) self.rank = self.device self.group = dist.group.WORLD self.print('[INFO] Training Options:', opt) if (self.world_size > 1): dist.init_process_group(backend='nccl', init_method='env://', world_size=self.world_size, rank=self.rank) self.model = None self.dicts = dicts self.opt = opt self.cuda = ((len(opt.gpus) >= 1) and (opt.gpus[0] >= 0)) if self.cuda: torch.cuda.set_device(self.device) assert self.cuda, '[ERROR] Training is only available on GPUs.' self.start_time = 0 torch.manual_seed(self.opt.seed) if self.is_main(): print('[INFO] Building models .... ', flush=True) print('Languages: ', dicts['langs'], flush=True) model = build_model(opt, dicts, False, self.constants) tgt_pad = dicts['tgt_pad'] if (opt.ctc_loss > 0.0): from onmt.speech.ctc_loss import CTC self.ctc_loss_function = CTC(dicts['tgt'].size(), opt.model_size, 0.0, reduce=True, padding_idx=tgt_pad, blank_idx=0) else: self.ctc_loss_function = None if (opt.predict_language > 0): from onmt.models.speech_recognizer.lid_loss import CrossEntropyLIDLoss self.lid_loss_function = CrossEntropyLIDLoss(opt.n_languages, label_smoothing=0.0) if opt.nce: from onmt.modules.nce.nce_loss import NCELoss loss_function = NCELoss(opt.model_size, dicts['tgt'].size(), noise_ratio=opt.nce_noise, logz=9, label_smoothing=opt.label_smoothing) else: loss_function = NMTLossFunc(opt.model_size, dicts['tgt'].size(), label_smoothing=opt.label_smoothing, mirror=opt.mirror_loss, padding_idx=tgt_pad) optimize_model(model, distributed=(self.world_size > 1)) if opt.load_pretrained_classifier: from onmt.model_factory import build_classifier self.print('Loading pretrained external classifier ...', flush=True) classifier_checkpoint = torch.load(opt.load_pretrained_classifier, map_location=(lambda storage, loc: storage)) classifier_opt = classifier_checkpoint['opt'] classifier_dicts = classifier_checkpoint['dicts'] self.classifier = build_classifier(classifier_opt, classifier_dicts) self.classifier.load_state_dict(classifier_checkpoint['model']) init_model_parameters(model, opt) self.model = model self.loss_function = loss_function self.grad_scaler = torch.cuda.amp.GradScaler() if opt.load_from: checkpoint = torch.load(opt.load_from, map_location=(lambda storage, loc: storage)) try: self.model.load_state_dict(checkpoint['model']) except RuntimeError as e: self.model.load_state_dict(checkpoint['model'], strict=True) if self.cuda: self.loss_function = self.loss_function.cuda(device=self.device) self.model = self.model.cuda(device=self.device) if (opt.ctc_loss > 0.0): self.ctc_loss_function = self.ctc_loss_function.cuda(device=self.device) if opt.load_pretrained_classifier: self.classifier = self.classifier.cuda(device=self.device) if setup_optimizer: self.optim = onmt.Optim(opt) self.optim.set_parameters(self.model.parameters()) if self.is_main(): print('[INFO] Optimizer: ', self.optim.optimizer) if (opt.load_from and (not opt.reset_optim)): if (('optim' in checkpoint) and (checkpoint['optim'] is not None) and (not opt.reset_optim)): self.optim.load_state_dict(checkpoint['optim']) if (opt.starting_step > 0): print(('[INFO] Optimizer starting from state %d ' % opt.starting_step)) self.optim.set_starting_step(opt.starting_step) if (self.world_size > 1): find_unused_parameters = opt.find_unused_parameters self.model = torch.nn.parallel.DistributedDataParallel(self.model, device_ids=[self.rank], output_device=self.rank, find_unused_parameters=find_unused_parameters) if self.is_main(): nparams = sum((p.numel() for p in model.parameters() if p.requires_grad)) print(('[INFO] Total number of trainable paramaters: %d' % nparams)) nparams = sum((p.numel() for p in model.parameters())) print(('[INFO] Total number of paramaters: %d' % nparams)) if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): self.model.module.is_main = True else: self.model.is_main = True if opt.load_fisher: if self.is_main(): print(('[INFO] Loading fisher information from: %s' % opt.load_fisher)) self.fisher_info = torch.load(opt.load_fisher, map_location=(lambda storage, loc: storage)) if self.cuda: for n in self.fisher_info['mean']: self.fisher_info['mean'][n] = self.fisher_info['mean'][n].cuda() for n in self.fisher_info['fisher_diag']: self.fisher_info['fisher_diag'][n] = self.fisher_info['fisher_diag'][n].cuda() else: self.fisher_info = None print(('[INFO] Process %d ready.' % self.rank), flush=True) def is_main(self): return (self.rank == 0) def all_reduce(self, tensor, **kwargs): if (self.world_size > 1): dist.all_reduce(tensor, **kwargs) return def print(self, *content, flush=False): if self.is_main(): print(*content, flush=flush) else: return def load_encoder_weight(self, checkpoint_file, wav2vec=False): if (not wav2vec): print(('Loading pretrained Encoder Weights from %s' % checkpoint_file), flush=True) checkpoint = torch.load(checkpoint_file, map_location=(lambda storage, loc: storage)) pretrained_model = build_model(checkpoint['opt'], checkpoint['dicts'], False, self.constants) pretrained_model.load_state_dict(checkpoint['model']) model = (self.model.module if (self.world_size > 1) else self.model) model.load_encoder_weights(pretrained_model) else: checkpoint = torch.load(checkpoint_file, map_location=(lambda storage, loc: storage)) model = (self.model.module if (self.world_size > 1) else self.model) model.load_encoder_weights(checkpoint) return def load_decoder_weight(self, checkpoint_file): self.print(('Loading pretrained models from %s' % checkpoint_file)) checkpoint = torch.load(checkpoint_file, map_location=(lambda storage, loc: storage)) chkpoint_dict = checkpoint['dicts'] pretrained_model = build_model(checkpoint['opt'], chkpoint_dict, False, self.constants) pretrained_model.load_state_dict(checkpoint['model']) self.print('Loading pretrained decoder weights ...') pretrained_word_emb = pretrained_model.decoder.word_lut pretrained_model.decoder.word_lut = None pretrained_lang_emb = pretrained_model.decoder.language_embeddings pretrained_model.decoder.language_embeddings = None untrained_word_emb = self.model.decoder.word_lut self.model.decoder.word_lut = None untrained_lang_emb = self.model.decoder.language_embeddings self.model.decoder.language_embeddings = None decoder_state_dict = pretrained_model.decoder.state_dict() self.model.decoder.load_state_dict(decoder_state_dict) n_copies = 0 for token in self.dicts['tgt'].labelToIdx: untrained_id = self.dicts['tgt'].labelToIdx[token] if (token in chkpoint_dict['tgt'].labelToIdx): pretrained_id = chkpoint_dict['tgt'].labelToIdx[token] untrained_word_emb.weight.data[untrained_id].copy_(pretrained_word_emb.weight.data[pretrained_id]) self.model.generator[0].linear.bias.data[untrained_id].copy_(pretrained_model.generator[0].linear.bias.data[pretrained_id]) n_copies += 1 self.print(('Copied embedding for %d words' % n_copies)) self.model.decoder.word_lut = untrained_word_emb if (pretrained_lang_emb and untrained_lang_emb and ('langs' in chkpoint_dict)): for lang in self.dicts['langs']: untrained_id = self.dicts['langs'][lang] if (lang in chkpoint_dict['langs']): pretrained_id = chkpoint_dict['langs'][lang] untrained_lang_emb.weight.data[untrained_id].copy_(pretrained_lang_emb.weight.data[pretrained_id]) self.model.decoder.language_embeddings = untrained_lang_emb def save(self, epoch, valid_ppl, itr=None): opt = self.opt model = self.model dicts = self.dicts if isinstance(model, torch.nn.parallel.DistributedDataParallel): model_state_dict = self.model.module.state_dict() else: model_state_dict = self.model.state_dict() optim_state_dict = self.optim.state_dict() if itr: itr_state_dict = itr.state_dict() else: itr_state_dict = None checkpoint = {'model': model_state_dict, 'dicts': dicts, 'opt': opt, 'epoch': epoch, 'itr': itr_state_dict, 'optim': optim_state_dict, 'scaler': self.grad_scaler.state_dict()} file_name = ('%s_ppl_%.6f_e%.2f.pt' % (opt.save_model, valid_ppl, epoch)) print(('Writing to %s' % file_name)) torch.save(checkpoint, file_name) checkpoint_dir = os.path.dirname(opt.save_model) existed_save_files = checkpoint_paths(checkpoint_dir) for save_file in existed_save_files[opt.keep_save_files:]: print((' * Deleting old save file %s ....' % save_file)) os.remove(save_file) def eval(self, data): self.print('[INFO] Running cross-entropy evaluation...', flush=True) opt = self.opt rank = self.rank world_size = self.world_size data_iterator = generate_data_iterator(data, rank, world_size, seed=self.opt.seed, num_workers=1, epoch=1, buffer_size=opt.buffer_size, split_even=False, dataset_ids=opt.valid_sets) epoch_iterator = data_iterator.next_epoch_itr(False, pin_memory=False) data_size = len(data_iterator) i = 0 self.model.eval() self.loss_function.eval() if opt.load_pretrained_classifier: self.classifier.eval() total_loss = zero_tensor() total_words = zero_tensor() total_correct = zero_tensor() if opt.streaming: streaming_state = self.model.init_stream() else: streaming_state = None with torch.no_grad(): while (i < len(epoch_iterator)): samples = next(epoch_iterator) def maybe_no_sync(): if isinstance(self.model, DDP_model): return self.model.no_sync() else: return contextlib.ExitStack() if samples: with maybe_no_sync(): with autocast(enabled=opt.fp16): batch = prepare_sample(samples, device=self.device) targets = batch.get('target_output') tgt_mask = targets.ne(onmt.constants.PAD) if opt.load_pretrained_classifier: layer_states = self.classifier.encode(batch) else: layer_states = None outputs = self.model(batch, streaming=opt.streaming, target_mask=tgt_mask, mirror=opt.mirror_loss, streaming_state=streaming_state, nce=opt.nce, pretrained_layer_states=layer_states, ctc_loss_function=self.ctc_loss_function, ctc_labels=targets, grad_scaler=self.grad_scaler, ctc_coeff=opt.ctc_loss) outputs['tgt_mask'] = tgt_mask loss_dict = self.loss_function(outputs, targets, model=self.model, eval=True) loss_data = loss_dict['data'] (correct, total) = (loss_dict['correct'], loss_dict['total']) assert (total == batch.tgt_size), ('Process %i, Minibatch %d/%d: Expected %d tokens from the batch, got %d' % (self.rank, i, data_size, batch.tgt_size, total)) total_loss.add_(loss_data) total_words.add_(batch.tgt_size) total_correct.add_(correct) i = (i + 1) self.all_reduce(total_loss, op=dist.ReduceOp.SUM, group=self.group) self.all_reduce(total_words, op=dist.ReduceOp.SUM, group=self.group) self.all_reduce(total_correct, op=dist.ReduceOp.SUM, group=self.group) if opt.use_memory: if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): model = self.model.module else: model = self.model if hasattr(model, 'memory_stats'): self.all_reduce(model.memory_stats, op=dist.ReduceOp.SUM, group=self.group) else: print('WARNING: Could not all_reduce in mp_trainer') self.model.train() self.loss_function.train() if opt.load_pretrained_classifier: self.classifier.train() return ((total_loss.item() / total_words.item()), (total_correct.item() / total_words.item())) def train_epoch(self, train_data, valid_data, epoch, resume=False, itr_progress=None): opt = self.opt streaming = opt.streaming grad_norm = (- 1) self.optim.zero_grad(set_to_none=opt.true_zero_grad) dataset = train_data data_iterator = generate_data_iterator(dataset, self.rank, self.world_size, seed=self.opt.seed, num_workers=opt.num_workers, epoch=epoch, buffer_size=opt.buffer_size, split_even=True, dataset_ids=opt.train_sets) if resume: data_iterator.load_state_dict(itr_progress) epoch_iterator = data_iterator.next_epoch_itr((not streaming), pin_memory=opt.pin_memory) (total_tokens, total_loss, total_words) = (zero_tensor(), zero_tensor(), zero_tensor()) total_non_pads = zero_tensor() (report_loss, report_tgt_words) = (zero_tensor(), zero_tensor()) report_ctc_loss = zero_tensor() report_ewc_loss = zero_tensor() report_ctc_targets = zero_tensor() report_ewc_count = 0 report_src_words = zero_tensor() report_sents = zero_tensor() (report_rec_loss, report_rev_loss, report_mirror_loss) = (zero_tensor(), zero_tensor(), zero_tensor()) report_enc_lid_loss = zero_tensor() report_enc_lid_count = 0 report_dec_lid_loss = zero_tensor() report_dec_lid_count = 0 start = time.time() n_samples = len(data_iterator) counter = 0 num_accumulated_words = zero_tensor() num_accumulated_sents = zero_tensor() report_contrastive_loss = zero_tensor() if opt.streaming: streaming_state = self.model.init_stream() else: streaming_state = None ewc_importance = opt.ewc_importance if (ewc_importance > 0): assert (self.fisher_info is not None) if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): model = self.model.module else: model = self.model parameters = dict() for (n, p) in model.named_parameters(): if ((n in self.fisher_info['mean']) and p.requires_grad): parameters[n] = p i = (data_iterator.iterations_in_epoch if (not is_list(train_data)) else epoch_iterator.n_yielded) i = (i * self.world_size) while (not data_iterator.end_of_epoch()): samples = next(epoch_iterator) batch = prepare_sample(samples, device=self.device) targets = batch.get('target_output') if opt.streaming: if train_data.is_new_stream(): streaming_state = self.model.init_stream() else: streaming_state = None oom = zero_tensor() counter = (counter + 1) reduce = (True if ((counter >= opt.update_frequency) or (i == (n_samples - 1))) else False) try: def maybe_no_sync(): if ((not reduce) and isinstance(self.model, DDP_model)): return self.model.no_sync() else: return contextlib.ExitStack() with maybe_no_sync(): with autocast(enabled=opt.fp16): tgt_mask = targets.ne(onmt.constants.PAD) if opt.load_pretrained_classifier: with torch.no_grad(): layer_states = self.classifier.encode(batch) else: layer_states = None outputs = self.model(batch, streaming=opt.streaming, target_mask=tgt_mask, zero_encoder=opt.zero_encoder, mirror=opt.mirror_loss, streaming_state=streaming_state, nce=opt.nce, pretrained_layer_states=layer_states, adv_ptb_grad=(opt.virtual_adversarial_training_mode > 0), checkpointing_ffn=opt.checkpointing_ffn, checkpointing_cross_attn=opt.checkpointing_cross_attn, checkpointing_self_attn=opt.checkpointing_self_attn, ctc_loss_function=self.ctc_loss_function, ctc_labels=targets, grad_scaler=self.grad_scaler, ctc_coeff=(opt.ctc_loss if (self.optim._step > opt.ctc_loss_delay) else 0.0)) batch_size = batch.size outputs['tgt_mask'] = tgt_mask loss_dict = self.loss_function(outputs, targets, model=self.model) loss_data = loss_dict['data'] loss = loss_dict['loss'] full_loss = loss if (opt.ctc_loss > 0.0): ctc_loss_data = outputs['ctc_loss'] n_ctc_targets = outputs['n_ctc_targets'] else: n_ctc_targets = 0 ctc_loss_data = 0 if opt.mirror_loss: rev_loss = loss_dict['rev_loss'] rev_loss_data = loss_dict['rev_loss_data'] mirror_loss = loss_dict['mirror_loss'] full_loss = ((full_loss + rev_loss) + mirror_loss) mirror_loss_data = loss_dict['mirror_loss'].item() else: rev_loss_data = None mirror_loss_data = 0 if (opt.predict_language > 0): enc_pred_lang = outputs['enc_pred_lang'] enc_mask = outputs['src_mask'] enc_lid_loss = self.lid_loss_function(enc_pred_lang, batch.get('source_lang'), enc_mask) dec_pred_lang = outputs['dec_pred_lang'] dec_mask = batch.get('target_input_selfattn_mask') dec_lid_loss = self.lid_loss_function(dec_pred_lang, batch.get('target_lang'), dec_mask) full_loss = (full_loss + (0.01 * (enc_lid_loss + dec_lid_loss))) report_enc_lid_loss.add_(enc_lid_loss.item()) report_enc_lid_count += enc_mask.ne(1).int().sum().item() report_dec_lid_loss.add_(dec_lid_loss.item()) report_dec_lid_count += dec_mask.ne(1).int().sum().item() else: enc_lid_loss = None enc_lid_loss_data = None dec_lid_loss = None dec_lid_loss_data = None if opt.reconstruct: rec_loss = loss_dict['rec_loss'] rec_loss = rec_loss full_loss = (full_loss + rec_loss) rec_loss_data = loss_dict['rec_loss_data'] else: rec_loss_data = None if (hasattr(opt, 'use_memory') and opt.use_memory and ('loss_memory' in outputs)): loss_memory = outputs['loss_memory'] full_loss = loss_memory if ((opt.contrastive_loss_coeff > 0) and ('contrastive_loss' in outputs)): contrastive_loss = outputs['contrastive_loss'] full_loss = (full_loss + (opt.contrastive_loss_coeff * contrastive_loss)) report_contrastive_loss.add_(contrastive_loss.item()) (correct, total) = (loss_dict['correct'], loss_dict['total']) optimizer = self.optim.optimizer grad_list = [p for p in self.model.parameters() if p.requires_grad] if (opt.virtual_adversarial_training_mode > 0): model_input = outputs['source'] vanilla_logits = outputs['logprobs'] grad_list += [model_input] else: model_input = None vanilla_logits = None self.grad_scaler.scale(full_loss).backward() if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): self.model.module.post_backward(output_dict=outputs) else: self.model.post_backward(output_dict=outputs) if (opt.virtual_adversarial_training_mode > 0): perturb = model_input.grad.data.new(*model_input.size()).copy_(model_input.grad.data) with autocast(enabled=opt.fp16): assert (model_input.grad is not None) outputs = self.model(batch, streaming=opt.streaming, target_mask=tgt_mask, pretrained_layer_states=layer_states, input_ptb=perturb) full_loss = None if (opt.virtual_adversarial_training_mode in [2, 3]): loss_dict = self.loss_function(outputs, targets, model=self.model) full_loss = loss_dict['loss'] if (opt.virtual_adversarial_training_mode in [1, 3]): logits = outputs['logprobs'] with torch.no_grad(): vanilla_probs = F.softmax(vanilla_logits.float().view((- 1), vanilla_logits.size((- 1))), dim=(- 1)) vanilla_probs.detach_() noisy_probs = F.softmax(logits.float().view((- 1), logits.view((- 1), logits.size((- 1)))), dim=(- 1)) kl_div_loss = F.kl_div(noisy_probs, vanilla_probs, reduction='sum') if (full_loss is None): full_loss = kl_div_loss else: full_loss += kl_div_loss grad_list = [p for p in self.model.parameters() if p.requires_grad] self.grad_scaler.scale(full_loss).backward() del outputs if ((self.optim._step % opt.ewc_decay_every) == 0): ewc_importance = (ewc_importance / opt.ewc_decay_scale) except RuntimeError as e: if ('out of memory' in str(e)): print(('[WARNING]: ran out of memory on GPU %d' % self.rank), flush=True) print('Input size at OOM position:', (batch.get('source').size() if (batch.get('source') is not None) else None), (batch.get('target').size() if (batch.get('target') is not None) else None)) raise e raise e batch_size = batch.size src_size = batch.src_size tgt_size = batch.tgt_size num_accumulated_words.add_(tgt_size) num_accumulated_sents.add_(batch_size) update_flag = reduce if update_flag: self.all_reduce(num_accumulated_words, op=dist.ReduceOp.SUM, group=self.group) grad_denom = 1.0 self.grad_scaler.unscale_(self.optim.optimizer) if self.opt.normalize_gradient: grad_denom = (num_accumulated_words.item() * grad_denom) else: grad_denom = 1 if (grad_denom != 1): normalize_gradients(self.model.parameters(), grad_denom) grad_norm = clip_grad_norm(self.model.parameters(), self.opt.max_grad_norm) if (ewc_importance > 0): ewc_penalty = 0 if (self.optim._step >= opt.ewc_delay): with self.model.no_sync(): for (n, p) in self.model.named_parameters(): if isinstance(self.model, DDP_model): n = n[len('module.'):] if (n in self.fisher_info['mean']): penalty = (self.fisher_info['fisher_diag'][n] * torch.square((p - self.fisher_info['mean'][n].data))) ewc_penalty = (ewc_penalty + penalty.sum()) loss = (ewc_penalty * ewc_importance) ewc_loss = ewc_penalty.item() loss.backward() report_ewc_loss.add_(ewc_loss) report_ewc_count += 1 self.optim.step(scaler=self.grad_scaler) self.grad_scaler.update() self.optim.zero_grad(set_to_none=opt.true_zero_grad) counter = 0 num_accumulated_words.zero_() num_accumulated_sents.zero_() num_updates = self.optim._step if (((opt.save_every > 0) and ((num_updates % opt.save_every) == ((- 1) % opt.save_every))) or (num_updates >= opt.max_step)): (valid_loss, valid_accuracy) = self.eval(valid_data) valid_ppl = math.exp(min(valid_loss, 100)) if self.is_main(): print(('Validation perplexity: %g' % valid_ppl)) print(('Validation accuracy: %g percent' % (100 * valid_accuracy))) ep = ((float(epoch) - 1.0) + ((float(i) + 1.0) / n_samples)) if (opt.save_metrics in ['ppl', 'perplexity']): value = valid_ppl elif (opt.save_metrics == 'memory'): if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): value = self.model.module.choose_best_epoch_by else: value = self.model.choose_best_epoch_by else: value = (1 - valid_accuracy) self.save(ep, value, itr=data_iterator) if (num_updates >= opt.max_step): print('[INFO] Max-training-step reached.') exit(0) num_words = tgt_size report_loss.add_(loss_data) report_tgt_words.add_(num_words) report_src_words.add_(src_size) total_loss.add_(loss_data) total_words.add_(num_words) report_sents.add_(1) if opt.reconstruct: report_rec_loss.add_(rec_loss_data) if opt.mirror_loss: report_rev_loss.add_(rev_loss_data) report_mirror_loss.add_(mirror_loss_data) if (opt.ctc_loss > 0.0): report_ctc_loss.add_(ctc_loss_data) report_ctc_targets.add_(n_ctc_targets) if ((i == 0) or (((i + 1) % opt.log_interval) < self.world_size)): self.all_reduce(report_loss, op=dist.ReduceOp.SUM, group=self.group) self.all_reduce(report_tgt_words, op=dist.ReduceOp.SUM, group=self.group) self.all_reduce(report_src_words, op=dist.ReduceOp.SUM, group=self.group) if self.is_main(): log_string = ('Epoch %2d, %5d/%5d; ; ppl: %6.2f ; grad_norm: %6.4f ' % (epoch, (i + 1), len(data_iterator), math.exp((report_loss.item() / report_tgt_words.item())), grad_norm)) if opt.mirror_loss: self.all_reduce(report_rev_loss, op=dist.ReduceOp.SUM, group=self.group) rev_ppl = math.exp((report_rev_loss.item() / report_tgt_words.item())) log_string += (' rev_ppl: %6.2f ; ' % rev_ppl) log_string += (' mir_loss: %6.2f ; ' % (report_mirror_loss / report_tgt_words)) if (opt.ctc_loss > 0.0): ctc_loss = (report_ctc_loss.item() / report_ctc_targets.item()) log_string += (' ctcloss: %8.2f ; ' % ctc_loss) if (opt.contrastive_loss_coeff > 0.0): ctv_loss = (report_contrastive_loss.item() / report_tgt_words.item()) log_string += (' ctv_loss: %8.2f ; ' % ctv_loss) if (ewc_importance > 0.0): try: _ewc_loss = (report_ewc_loss.item() / report_ewc_count) except ZeroDivisionError: _ewc_loss = float('nan') log_string += (' ewcloss: %8.8f ; ' % _ewc_loss) if (opt.predict_language > 0): try: _enc_lid_loss = (report_enc_lid_loss.item() / report_enc_lid_count) _dec_lid_loss = (report_dec_lid_loss.item() / report_dec_lid_count) except ZeroDivisionError: _enc_lid_loss = float('nan') _dec_lid_loss = float('nan') log_string += (' enc_lidloss: %8.8f ; ' % _enc_lid_loss) log_string += (' dec_lidloss: %8.8f ; ' % _dec_lid_loss) log_string += ('lr: %.7f ; updates: %7d; ' % (self.optim.get_learning_rate(), self.optim._step)) log_string += ('%5.0f src tok/s; %5.0f tgt tok/s; ' % ((report_src_words.item() / (time.time() - start)), (report_tgt_words.item() / (time.time() - start)))) log_string += ('%s elapsed' % str(datetime.timedelta(seconds=int((time.time() - self.start_time))))) self.print(log_string, flush=True) report_loss.zero_() report_tgt_words.zero_() report_src_words.zero_() report_rec_loss.zero_() report_rev_loss.zero_() report_mirror_loss.zero_() report_ctc_loss.zero_() report_ctc_targets.zero_() report_ewc_loss.zero_() report_ewc_count = 0 if (report_contrastive_loss is not None): report_contrastive_loss.zero_() start = time.time() i = (i + self.world_size) return (total_loss / total_words) def estimate_fisher(self, data): def is_factorize_params(p_name): if (p_name.endswith('.r_i') or p_name.endswith('.s_i') or p_name.endswith('.r_o') or p_name.endswith('.s_o') or p_name.endswith('.r_p') or p_name.endswith('.s_p')): return True if (p_name.endswith('.r_q') or p_name.endswith('.s_q') or p_name.endswith('.r_o') or p_name.endswith('.s_o') or p_name.endswith('.r_kv') or p_name.endswith('.s_kv')): return True if (p_name.endswith('.rm_q') or p_name.endswith('.sm_q') or p_name.endswith('.rm_o') or p_name.endswith('.sm_o') or p_name.endswith('.rm_kv') or p_name.endswith('.sm_kv')): return True if (p_name.endswith('.sub_r_i') or p_name.endswith('.sub_s_i') or p_name.endswith('.sub_r_o') or p_name.endswith('.sub_s_o') or p_name.endswith('.sub_r_p') or p_name.endswith('.sub_s_p')): return True if (p_name.endswith('.sub_r_q') or p_name.endswith('.sub_s_q') or p_name.endswith('.sub_r_o') or p_name.endswith('.sub_s_o') or p_name.endswith('.sub_r_kv') or p_name.endswith('.sub_s_kv')): return True if (p_name.endswith('.sub_rm_q') or p_name.endswith('.sub_sm_q') or p_name.endswith('.sub_rm_o') or p_name.endswith('.sub_sm_o') or p_name.endswith('.sub_rm_kv') or p_name.endswith('.sub_sm_kv')): return True if (p_name.endswith('.rm_i') or p_name.endswith('.sm_i') or p_name.endswith('.rm_o') or p_name.endswith('.sm_o') or p_name.endswith('.rm_p') or p_name.endswith('.sm_p')): return True if (p_name.endswith('.sub_rm_i') or p_name.endswith('.sub_sm_i') or p_name.endswith('.sub_rm_o') or p_name.endswith('.sub_sm_o') or p_name.endswith('.sub_rm_p') or p_name.endswith('.sub_sm_p')): return True if ('adapter' in p_name): return True return False if (self.rank == 0): print('[INFO] Estimating fisher information ...\n') opt = self.opt epoch = 0 assert (len(opt.load_from) > 0) self.optim.zero_grad(set_to_none=False) if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): model = self.model.module else: model = self.model parameters = {n: p for (n, p) in model.named_parameters() if p.requires_grad} precision_matrices = dict() for (n, p) in parameters.items(): if (not is_factorize_params(n)): precision_matrices[n] = torch.zeros_like(p) dataset = data data_iterator = generate_data_iterator(dataset, self.rank, self.world_size, seed=self.opt.seed, num_workers=opt.num_workers, epoch=0, buffer_size=opt.buffer_size, split_even=True, dataset_ids=opt.train_sets) streaming = False epoch_iterator = data_iterator.next_epoch_itr((not streaming), pin_memory=opt.pin_memory) (total_tokens, total_loss, total_words) = (zero_tensor(), zero_tensor(), zero_tensor()) total_non_pads = zero_tensor() (report_loss, report_tgt_words) = (zero_tensor(), zero_tensor()) report_ctc_loss = zero_tensor() report_ctc_targets = zero_tensor() report_src_words = zero_tensor() (report_rec_loss, report_rev_loss, report_mirror_loss) = (zero_tensor(), zero_tensor(), zero_tensor()) start = time.time() n_samples = len(data_iterator) counter = 0 num_accumulated_words = zero_tensor() num_accumulated_sents = zero_tensor() report_contrastive_loss = zero_tensor() if opt.streaming: streaming_state = self.model.init_stream() else: streaming_state = None i = (data_iterator.iterations_in_epoch if (not is_list(dataset)) else epoch_iterator.n_yielded) i = (i * self.world_size) self.model.train() while (not data_iterator.end_of_epoch()): samples = next(epoch_iterator) batch = prepare_sample(samples, device=self.device) targets = batch.get('target_output') if opt.streaming: if train_data.is_new_stream(): streaming_state = self.model.init_stream() else: streaming_state = None oom = zero_tensor() counter = (counter + 1) reduce = False try: def maybe_no_sync(): if ((not reduce) and isinstance(self.model, DDP_model)): return self.model.no_sync() else: return contextlib.ExitStack() with maybe_no_sync(): with autocast(enabled=opt.fp16): tgt_mask = targets.ne(onmt.constants.PAD) if opt.load_pretrained_classifier: with torch.no_grad(): layer_states = self.classifier.encode(batch) else: layer_states = None outputs = self.model(batch, streaming=opt.streaming, target_mask=tgt_mask, zero_encoder=opt.zero_encoder, mirror=opt.mirror_loss, streaming_state=streaming_state, nce=opt.nce, pretrained_layer_states=layer_states, adv_ptb_grad=(opt.virtual_adversarial_training_mode > 0), checkpointing_ffn=opt.checkpointing_ffn, checkpointing_cross_attn=opt.checkpointing_cross_attn, checkpointing_self_attn=opt.checkpointing_self_attn, ctc_loss_function=self.ctc_loss_function, ctc_labels=targets, grad_scaler=self.grad_scaler) batch_size = batch.size outputs['tgt_mask'] = tgt_mask loss_dict = self.loss_function(outputs, targets, model=self.model) loss_data = loss_dict['data'] loss = loss_dict['loss'] full_loss = loss if (opt.ctc_loss > 0.0): ctc_loss = outputs['ctc_loss'] full_loss = (full_loss + ctc_loss) if opt.mirror_loss: rev_loss = loss_dict['rev_loss'] rev_loss_data = loss_dict['rev_loss_data'] mirror_loss = loss_dict['mirror_loss'] full_loss = ((full_loss + rev_loss) + mirror_loss) mirror_loss_data = loss_dict['mirror_loss'].item() else: rev_loss_data = None mirror_loss_data = 0 if opt.reconstruct: rec_loss = loss_dict['rec_loss'] rec_loss = rec_loss full_loss = (full_loss + rec_loss) rec_loss_data = loss_dict['rec_loss_data'] else: rec_loss_data = None if ((opt.contrastive_loss_coeff > 0) and ('contrastive_loss' in outputs)): contrastive_loss = outputs['contrastive_loss'] full_loss = (full_loss + (opt.contrastive_loss_coeff * contrastive_loss)) report_contrastive_loss.add_(contrastive_loss.item()) (correct, total) = (loss_dict['correct'], loss_dict['total']) optimizer = self.optim.optimizer grad_list = [p for p in self.model.parameters() if p.requires_grad] if (opt.virtual_adversarial_training_mode > 0): model_input = outputs['source'] vanilla_logits = outputs['logprobs'] grad_list += [model_input] else: model_input = None vanilla_logits = None self.grad_scaler.scale(full_loss).backward() self.model.post_backward(output_dict=outputs) except RuntimeError as e: if ('out of memory' in str(e)): print(('[WARNING]: ran out of memory on GPU %d' % self.rank), flush=True) print('Input size at OOM position:', batch.get('source').size(), batch.get('target').size()) raise e batch_size = batch.size src_size = batch.src_size tgt_size = batch.tgt_size num_accumulated_words.add_(tgt_size) num_accumulated_sents.add_(batch_size) self.grad_scaler.unscale_(self.optim.optimizer) grad_norm = clip_grad_norm(self.model.parameters(), 0) self.grad_scaler.update() for (n, p) in parameters.items(): if (n in precision_matrices): grad = p.grad.data grad.masked_fill_(torch.logical_or(torch.isinf(grad), torch.isnan(grad)), 0) precision_matrices[n].add_(torch.square(p.grad.data)) self.optim.zero_grad(set_to_none=opt.true_zero_grad) counter = 0 num_words = tgt_size report_loss.add_(loss_data) report_tgt_words.add_(num_words) report_src_words.add_(src_size) total_loss.add_(loss_data) total_words.add_(num_words) if ((i == 0) or (((i + 1) % opt.log_interval) < self.world_size)): self.all_reduce(report_loss, op=dist.ReduceOp.SUM, group=self.group) self.all_reduce(report_tgt_words, op=dist.ReduceOp.SUM, group=self.group) self.all_reduce(report_src_words, op=dist.ReduceOp.SUM, group=self.group) self.all_reduce(report_contrastive_loss, op=dist.ReduceOp.SUM, group=self.group) if self.is_main(): log_string = ('Epoch %2d, %5d/%5d; ; ppl: %6.2f ; grad_norm: %6.4f; gradscaler: %9.9f ' % (epoch, (i + 1), len(data_iterator), math.exp((report_loss.item() / report_tgt_words.item())), grad_norm, self.grad_scaler.get_scale())) log_string += ('lr: %.7f ; updates: %7d; ' % (self.optim.get_learning_rate(), self.optim._step)) log_string += ('%5.0f src tok/s; %5.0f tgt tok/s; ' % ((report_src_words.item() / (time.time() - start)), (report_tgt_words.item() / (time.time() - start)))) log_string += ('%s elapsed' % str(datetime.timedelta(seconds=int((time.time() - self.start_time))))) self.print(log_string, flush=True) report_loss.zero_() report_tgt_words.zero_() report_src_words.zero_() report_rec_loss.zero_() report_rev_loss.zero_() report_mirror_loss.zero_() report_ctc_loss.zero_() if (report_contrastive_loss is not None): report_contrastive_loss.zero_() start = time.time() i = (i + self.world_size) if isinstance(self.model, DDP_model): torch.cuda.synchronize(device=self.rank) loss = 0 for (n, p) in parameters.items(): loss = (loss + (p.sum() * 0)) loss.backward() self.all_reduce(num_accumulated_words, op=dist.ReduceOp.SUM, group=self.group) if (self.world_size > 1): if (self.rank == 0): print('[INFO] Synchronizing precision matrices') for n in precision_matrices: self.all_reduce(precision_matrices[n], op=dist.ReduceOp.SUM, group=self.group) if (self.rank == 0): print('Done...') if (self.rank == 0): if (self.fisher_info is not None): print('[INFO] Accumulating fisher information from a previous iteration...') for n in precision_matrices: if (n in self.fisher_info): precision_matrices[n] = (self.fisher_info['fisher_diag'][n] + precision_matrices[n]) means = dict() for (n, p) in parameters.items(): if (n in precision_matrices): means[n] = p checkpoint = {'mean': means, 'fisher_diag': precision_matrices, 'opt': opt} file_name = (opt.load_from + '.fisher') print(('[INFO] Saving means and fisher information to %s' % file_name)) torch.save(checkpoint, file_name) return (total_loss / total_words) def run(self, train_data=None, valid_data=None, checkpoint=None): opt = self.opt if opt.cache_encoder_output: import onmt.data.indexed_file as indexed_file import hashlib worked = False for datasets in [valid_data, train_data]: for (i, dataset) in enumerate(datasets): id = hashlib.sha256(dataset.src_sizes.tobytes()).hexdigest() basename_e = ((opt.cache_dir + 'encoder_features_') + id) name1_e = (basename_e + '.data') name2_e = (basename_e + '.index') if (os.path.isfile(name1_e) and os.path.isfile(name2_e)): dataset.encoder_feature_files = (name1_e, torch.load(name2_e)) print('Using cached features:', id, 'for dataset', i) continue print('Caching features:', id) breakpoint() dataset.index = 0 dataset.anz_sets = 1 worked = True self.model.eval() with open(name2_e, 'w') as f: f.write('In progress') file_data_e = open(name1_e, 'wb') file_index_e = {} iterator = generate_data_iterator(dataset, 0, 1, self.opt.seed, num_workers=8) iterator = iterator.next_epoch_itr(shuffle=False) for samples in tqdm(iterator): batch = prepare_sample(samples, device=self.device) with torch.no_grad(): with autocast(enabled=self.opt.fp16): output = self.model(batch) context = output['context'].transpose(1, 0) mask = output['src_mask'].eq(0).sum((- 1)) indices = batch.tensors['indices'] for (index, con, frames) in zip(indices, context, mask): data = con[:frames] indexed_file.add_data(file_data_e, file_index_e, index, data) 'context = output["hidden"].transpose(1,0)\n labels = batch.tensors["target_output"].transpose(1,0)\n mask = labels.ge(2).sum(-1)\n\n for index, con, tokens, label in zip(indices,context,mask,labels):\n data = con[:tokens]\n indexed_file.add_data(file_data_d, file_index_d, index, data)\n label_d[index] = label[:tokens]' file_data_e.close() torch.save(file_index_e, name2_e) print('Finished caching features:', id) if worked: print('Caching finished, exiting.') sys.exit() if (checkpoint is not None): prec_opt = (checkpoint['opt'] if ('opt' in checkpoint) else None) if (not opt.reset_optim): itr_progress = None resume = True start_epoch = ((math.floor(checkpoint['epoch']) + 1) if ('epoch' in checkpoint) else 1) if (start_epoch is None): start_epoch = 1 else: itr_progress = None resume = False start_epoch = 1 del checkpoint else: itr_progress = None resume = False start_epoch = 1 if opt.load_encoder_from: self.load_encoder_weight(opt.load_encoder_from) if opt.load_decoder_from: self.load_decoder_weight(opt.load_decoder_from) if opt.estimate_fisher_information: self.start_time = time.time() self.estimate_fisher(train_data) return if (opt.run_validation_before_training or (opt.max_step <= 0)): (valid_loss, valid_accuracy) = self.eval(valid_data) valid_ppl = math.exp(min(valid_loss, 100)) if self.is_main(): print(('[INFO] Validation perplexity: %g' % valid_ppl), flush=True) print(('[INFO] Validation accuracy: %g percent' % (100 * valid_accuracy))) if (opt.max_step <= 0): if self.is_main(): self.save(0, (valid_ppl if (opt.save_metrics in ['ppl', 'perplexity']) else (1 - valid_accuracy))) return self.start_time = time.time() for epoch in range(start_epoch, (start_epoch + opt.epochs)): self.print('') train_loss = self.train_epoch(train_data, valid_data, epoch, resume=resume, itr_progress=itr_progress) train_ppl = math.exp(min(train_loss, 100)) self.print(('[INFO] Train perplexity: %g' % train_ppl)) (valid_loss, valid_accuracy) = self.eval(valid_data) valid_ppl = math.exp(min(valid_loss, 100)) if self.is_main(): print(('[INFO] Validation perplexity: %g' % valid_ppl)) print(('[INFO] Validation accuracy: %g percent' % (100 * valid_accuracy))) if (opt.save_metrics in ['ppl', 'perplexity']): value = valid_ppl elif (opt.save_metrics == 'memory'): if isinstance(self.model, torch.nn.parallel.DistributedDataParallel): value = self.model.module.choose_best_epoch_by else: value = self.model.choose_best_epoch_by else: value = (1 - valid_accuracy) self.save(epoch, value) itr_progress = None resume = False
class TestSetScreenSaver(EndianTest): def setUp(self): self.req_args_0 = {'allow_exposures': 2, 'interval': (- 25214), 'prefer_blank': 0, 'timeout': (- 24531)} self.req_bin_0 = b'k\x00\x00\x03\xa0-\x9d\x82\x00\x02\x00\x00' def testPackRequest0(self): bin = request.SetScreenSaver._request.to_binary(*(), **self.req_args_0) self.assertBinaryEqual(bin, self.req_bin_0) def testUnpackRequest0(self): (args, remain) = request.SetScreenSaver._request.parse_binary(self.req_bin_0, dummy_display, 1) self.assertBinaryEmpty(remain) self.assertEqual(args, self.req_args_0)
class AttrVI_ATTR_USB_INTFC_NUM(RangeAttribute): resources = [(constants.InterfaceType.usb, 'INSTR'), (constants.InterfaceType.usb, 'RAW')] py_name = 'interface_number' visa_name = 'VI_ATTR_USB_INTFC_NUM' visa_type = 'ViInt16' default = 0 (read, write, local) = (True, False, False) (min_value, max_value, values) = (0, 254, None)
def show_account_sub(call, email): t = f''' <code>{email}</code> ''' bot.edit_message_text(text=(t + '...'), chat_id=call.from_user.id, message_id=call.message.message_id, parse_mode='HTML') refresh_token = RefreshToken().get(email) az_sub = Subscription(refresh_token) subs = az_sub.list() for sub in subs: t += f''': <code>{sub['display_name']}</code> : <code>{sub['state']}</code> ''' markup = types.InlineKeyboardMarkup() markup.add(types.InlineKeyboardButton(text='', callback_data=('ma:rm:' + email))) bot.edit_message_text(text=t, chat_id=call.from_user.id, message_id=call.message.message_id, reply_markup=markup, parse_mode='HTML')
def test_spectral_factor_firstsolar_range(): with pytest.warns(UserWarning, match='Exceptionally high pw values'): out = spectrum.spectral_factor_firstsolar(np.array([0.1, 3, 10]), np.array([1, 3, 5]), module_type='monosi') expected = np.array([0., 1., np.nan]) assert_allclose(out, expected, atol=0.001) with pytest.warns(UserWarning, match='Exceptionally high pw values'): out = spectrum.spectral_factor_firstsolar(6, 1.5, max_precipitable_water=5, module_type='monosi') with pytest.warns(UserWarning, match='Exceptionally low pw values'): out = spectrum.spectral_factor_firstsolar(np.array([0, 3, 8]), np.array([1, 3, 5]), module_type='monosi') expected = np.array([0., 1., 1.]) assert_allclose(out, expected, atol=0.001) with pytest.warns(UserWarning, match='Exceptionally low pw values'): out = spectrum.spectral_factor_firstsolar(0.2, 1.5, min_precipitable_water=1, module_type='monosi')
def make_result_folders(output_directory): image_directory = os.path.join(output_directory, 'images') if (not os.path.exists(image_directory)): print('Creating directory: {}'.format(image_directory)) os.makedirs(image_directory) checkpoint_directory = os.path.join(output_directory, 'checkpoints') if (not os.path.exists(checkpoint_directory)): print('Creating directory: {}'.format(checkpoint_directory)) os.makedirs(checkpoint_directory) return (checkpoint_directory, image_directory)
.skipif((not torch.cuda.is_available()), reason='requires CUDA support') .parametrize('channels', [4, 30, 32, 64, 71, 1025]) def test_gradient_numerical(channels, grad_value=True, grad_sampling_loc=True, grad_attn_weight=True): (N, M, _) = (1, 2, 2) (Lq, L, P) = (2, 2, 2) shapes = torch.as_tensor([(3, 2), (2, 1)], dtype=torch.long).cuda() level_start_index = torch.cat((shapes.new_zeros((1,)), shapes.prod(1).cumsum(0)[:(- 1)])) S = sum([(H * W).item() for (H, W) in shapes]) value = (torch.rand(N, S, M, channels).cuda() * 0.01) sampling_locations = torch.rand(N, Lq, M, L, P, 2).cuda() attention_weights = (torch.rand(N, Lq, M, L, P).cuda() + 1e-05) attention_weights /= attention_weights.sum((- 1), keepdim=True).sum((- 2), keepdim=True) im2col_step = 2 func = MultiScaleDeformableAttnFunction.apply value.requires_grad = grad_value sampling_locations.requires_grad = grad_sampling_loc attention_weights.requires_grad = grad_attn_weight if _USING_PARROTS: assert gradcheck(func, (value.double(), shapes, level_start_index, sampling_locations.double(), attention_weights.double(), im2col_step), no_grads=[shapes, level_start_index]) else: assert gradcheck(func, (value.double(), shapes, level_start_index, sampling_locations.double(), attention_weights.double(), im2col_step))
class Plugin(): PLUGIN_ID: ClassVar[str] = xbmcaddon.Addon().getAddonInfo('id') PLUGIN_URL: ClassVar[str] = f'plugin://{PLUGIN_ID}' settings: ClassVar[Settings] = Settings() def __init__(self) -> None: self.path = (urlsplit(sys.argv[0]).path or '/') self.handle = int(sys.argv[1]) self.kwargs = dict(parse_qsl(sys.argv[2].lstrip('?'))) self.auth = Auth(self) self.logger = Logger(self) self.routing = Routing(self) self.search_history = SearchHistory(self) self.main_menu_items = self._main_menu_items() self.items = ItemsCollection(self) self.client = KinoPubClient(self) def list_item(self, *, name: str, label2: str='', iconImage: str='', thumbnailImage: str='', path: str='', poster: Optional[str]=None, fanart: Optional[str]=None, video_info: Optional[Dict]=None, properties: Optional[Dict[(str, Any)]]=None, addContextMenuItems: bool=False, subtitles: Optional[List[str]]=None) -> ExtendedListItem: return ExtendedListItem(name=name, label2=label2, iconImage=iconImage, thumbnailImage=thumbnailImage, path=path, poster=poster, fanart=fanart, video_info=video_info, properties=properties, addContextMenuItems=addContextMenuItems, subtitles=subtitles, plugin=self) def run(self) -> None: self.routing.dispatch(self.path) def _main_menu_items(self) -> List[MainMenuItem]: return [MainMenuItem(localize(32047), self.routing.build_url('profile/'), self.routing.build_icon_path('profile'), False, True), MainMenuItem(localize(32019), self.routing.build_url('search', 'all/'), self.routing.build_icon_path('search'), True, self.settings.show_search), MainMenuItem(localize(32048), self.routing.build_url('bookmarks/'), self.routing.build_icon_path('bookmarks'), True, True), MainMenuItem(localize(32049), self.routing.build_url('watching/'), self.routing.build_icon_path('watching'), True, True), MainMenuItem(localize(32050), self.routing.build_url('watching_movies/'), self.routing.build_icon_path('watching_movies'), True, True), MainMenuItem(localize(32020), self.routing.build_url('items', 'all', 'fresh/'), self.routing.build_icon_path('fresh'), True, self.settings.show_last), MainMenuItem(localize(32022), self.routing.build_url('items', 'all', 'popular/'), self.routing.build_icon_path('popular'), True, self.settings.show_popular), MainMenuItem(localize(32021), self.routing.build_url('items', 'all', 'hot/'), self.routing.build_icon_path('hot'), True, self.settings.show_hot), MainMenuItem(self.sorting_title, self.routing.build_url('items', 'all', 'sort/'), self.routing.build_icon_path('sort'), True, self.settings.show_sort), MainMenuItem(localize(32051), self.routing.build_url('tv/'), self.routing.build_icon_path('tv'), True, self.settings.show_tv), MainMenuItem(localize(32052), self.routing.build_url('collections/'), self.routing.build_icon_path('collections'), True, self.settings.show_collections), MainMenuItem(localize(32053), self.routing.build_url('items', 'movies/'), self.routing.build_icon_path('movies'), True, self.settings.show_movies), MainMenuItem(localize(32054), self.routing.build_url('items', 'serials/'), self.routing.build_icon_path('serials'), True, self.settings.show_serials), MainMenuItem(localize(32055), self.routing.build_url('items', 'tvshow/'), self.routing.build_icon_path('tvshows'), True, self.settings.show_tvshows), MainMenuItem('3D', self.routing.build_url('items', '3d/'), self.routing.build_icon_path('3d'), True, self.settings.show_3d), MainMenuItem(localize(32056), self.routing.build_url('items', 'concerts/'), self.routing.build_icon_path('concerts'), True, self.settings.show_concerts), MainMenuItem(localize(32057), self.routing.build_url('items', 'documovies/'), self.routing.build_icon_path('documovies'), True, self.settings.show_documovies), MainMenuItem(localize(32058), self.routing.build_url('items', 'docuserials/'), self.routing.build_icon_path('docuserials'), True, self.settings.show_docuserials)] def sorting_title(self) -> str: sd = self.settings.sorting_direction_title sb = self.settings.sort_by_localized return f'{localize(32089)} {sb} {sd}' def sorting_params(self) -> Dict[(str, str)]: return {'sort': f'{self.settings.sort_by}{self.settings.sorting_direction_param}'} def clear_window_property(self) -> None: xbmcgui.Window(10000).clearProperty('video.kino.pub-playback_data') def set_window_property(self, value: Dict) -> None: self.clear_window_property() pickled = codecs.encode(pickle.dumps(value), 'base64').decode('utf-8') xbmcgui.Window(10000).setProperty('video.kino.pub-playback_data', pickled) def get_window_property(self, item_id: str) -> Union[(TVShow, Multi, Movie)]: try: data = xbmcgui.Window(10000).getProperty('video.kino.pub-playback_data').encode('utf-8') items = pickle.loads(codecs.decode(data, 'base64')) except EOFError: items = {} item = items.get(int(item_id), {}) if item: item._plugin = self return item def is_hls_enabled(self) -> bool: return (('hls' in self.settings.stream_type) and (self.settings.use_inputstream_adaptive == 'true') and inputstreamhelper)
def test_nested_process_search_unsupported_field(s1_product: SentinelOne): criteria = {'foo': 'bar'} s1_product._queries = {} s1_product._pq = False s1_product.log = logging.getLogger('pytest_surveyor') s1_product.nested_process_search(Tag('unsupported_field'), criteria, {}) assert (len(s1_product._queries) == 0)
def cov_xPrime_maxGrad(xPrime, value_at_max, sigma, l): d = len(value_at_max) num_of_xPrime = len(xPrime) cov_matrix = np.zeros((num_of_xPrime, d)) for i in range(num_of_xPrime): for j in range(d): cov_matrix[(i, j)] = cov_x_devY(xPrime[i], value_at_max, sigma, l, j) return cov_matrix
class Finder(): def __init__(self, path: (Sequence[str] | None)=None) -> None: self._path = (path or sys.path) def find_module(self, modname: str, module_parts: Sequence[str], processed: list[str], submodule_path: (Sequence[str] | None)) -> (ModuleSpec | None): def contribute_to_path(self, spec: ModuleSpec, processed: list[str]) -> (Sequence[str] | None):
_module() class ImageToTensor(object): def __init__(self, keys): self.keys = keys def __call__(self, results): for key in self.keys: img = results[key] if (len(img.shape) < 3): img = np.expand_dims(img, (- 1)) results[key] = to_tensor(img.transpose(2, 0, 1)) return results def __repr__(self): return (self.__class__.__name__ + f'(keys={self.keys})')
('/api/file_system/create_folder', methods=['POST']) def create_folders() -> Response: request_json = request.get_json() (user_id, chat_id) = get_user_and_chat_id_from_request_json(request_json) root_path = create_personal_folder(user_id) if (os.path.exists(root_path) and os.path.isdir(root_path)): try: new_path = _generate_directory_name(os.path.join(root_path, 'Folder')) os.makedirs(new_path, exist_ok=False) logger.bind(user_id=user_id, chat_id=chat_id, api='/create_folder', msg_head='Create folder success').debug(new_path) return jsonify({'success': True, 'message': 'Folder created successfully'}) except Exception as e: logger.bind(user_id=user_id, chat_id=chat_id, api='/create_folder', msg_head='Create folder failed').error(str(e)) return jsonify({'success': False, 'message': str(e)}) else: logger.bind(user_id=user_id, chat_id=chat_id, api='/create_folder', msg_head='Create folder failed').error('Root path does not exist.') return Response(response=None, status=f'{INTERNAL} Root path does not exist')
def dropNested(text, openDelim, closeDelim): openRE = re.compile(openDelim, re.IGNORECASE) closeRE = re.compile(closeDelim, re.IGNORECASE) spans = [] nest = 0 start = openRE.search(text, 0) if (not start): return text end = closeRE.search(text, start.end()) next = start while end: next = openRE.search(text, next.end()) if (not next): while nest: nest -= 1 end0 = closeRE.search(text, end.end()) if end0: end = end0 else: break spans.append((start.start(), end.end())) break while (end.end() < next.start()): if nest: nest -= 1 last = end.end() end = closeRE.search(text, end.end()) if (not end): if spans: span = (spans[0][0], last) else: span = (start.start(), last) spans = [span] break else: spans.append((start.start(), end.end())) start = next end = closeRE.search(text, next.end()) break if (next != start): nest += 1 return dropSpans(spans, text)
class TapBpm(SongsMenuPlugin): PLUGIN_ID = 'Tap BPM' PLUGIN_NAME = _('Tap BPM') PLUGIN_DESC = _(' Tap BPM for the selected song.') PLUGIN_ICON = Icons.EDIT PLUGIN_VERSION = '0.1' def plugin_song(self, song): self._window = window = Dialog(title=_('Tap BPM'), parent=self.plugin_window) window.add_button(_('_Cancel'), Gtk.ResponseType.CANCEL) window.add_icon_button(_('_Save'), Icons.DOCUMENT_SAVE, Gtk.ResponseType.OK) window.set_default_size(300, 100) window.set_border_width(6) self.__resp_sig = window.connect('response', self.response) self._panel = TapBpmPanel(window, song) window.vbox.pack_start(self._panel, False, True, 0) window.vbox.show_all() window.present() def response(self, win, response): if (response == Gtk.ResponseType.OK): self._panel.save() win.hide() win.disconnect(self.__resp_sig) win.destroy()
class GreasemonkeyScript(): def __init__(self, properties, code, filename=None): self._code = code self.includes: Sequence[str] = [] self.matches: Sequence[str] = [] self.excludes: Sequence[str] = [] self.requires: Sequence[str] = [] self.description = None self.namespace = None self.run_at = None self.script_meta = None self.runs_on_sub_frames = True self.jsworld = 'main' self.name = '' self.dedup_suffix = 1 for (name, value) in properties: if (name == 'name'): self.name = value elif (name == 'namespace'): self.namespace = value elif (name == 'description'): self.description = value elif (name == 'include'): self.includes.append(value) elif (name == 'match'): self.matches.append(value) elif (name in ['exclude', 'exclude_match']): self.excludes.append(value) elif (name == 'run-at'): self.run_at = value elif (name == 'noframes'): self.runs_on_sub_frames = False elif (name == 'require'): self.requires.append(value) elif (name == 'qute-js-world'): self.jsworld = value if (not self.name): if filename: self.name = filename else: raise ValueError(' key required or pass filename to init.') HEADER_REGEX = '// ==UserScript==|\\n+// ==/UserScript==\\n' PROPS_REGEX = '// (?P<prop>[^\\s]+)\\s*(?P<val>.*)' def __str__(self): return self.name def full_name(self) -> str: parts = ['GM-'] if (self.namespace is not None): parts += [self.namespace, '/'] parts.append(self.name) if (self.dedup_suffix > 1): parts.append(f'-{self.dedup_suffix}') return ''.join(parts) def parse(cls, source, filename=None): matches = re.split(cls.HEADER_REGEX, source, maxsplit=2) try: (_head, props, _code) = matches except ValueError: props = '' script = cls(re.findall(cls.PROPS_REGEX, props), source, filename=filename) script.script_meta = props if ((not script.includes) and (not script.matches)): script.includes = ['*'] return script def needs_document_end_workaround(self): if (objects.backend == usertypes.Backend.QtWebKit): return False assert (objects.backend == usertypes.Backend.QtWebEngine), objects.backend broken_scripts = [(' None), (' 'Iridium')] return any((self._matches_id(namespace=namespace, name=name) for (namespace, name) in broken_scripts)) def _matches_id(self, *, namespace, name): matches_namespace = ((namespace is None) or (self.namespace == namespace)) matches_name = ((name is None) or (self.name == name)) return (matches_namespace and matches_name) def code(self): use_proxy = (not ((objects.backend == usertypes.Backend.QtWebKit) and (version.qWebKitVersion() == '602.1'))) template = jinja.js_environment.get_template('greasemonkey_wrapper.js') return template.render(scriptName=javascript.string_escape('/'.join([(self.namespace or ''), self.name])), scriptInfo=self._meta_json(), scriptMeta=javascript.string_escape((self.script_meta or '')), scriptSource=self._code, use_proxy=use_proxy) def _meta_json(self): return json.dumps({'name': self.name, 'description': self.description, 'matches': self.matches, 'includes': self.includes, 'excludes': self.excludes, 'run-at': self.run_at}) def add_required_script(self, source): self._code = '\n'.join([textwrap.indent(source, ' '), self._code])
def test_h11_as_server() -> None: with socket_server(H11RequestHandler) as (host, port) = url = f' with closing(urlopen(url)) as f: assert (f.getcode() == 200) data = f.read() info = json.loads(data.decode('ascii')) print(info) assert (info['method'] == 'GET') assert (info['target'] == '/some-path') assert ('urllib' in info['headers']['user-agent'])
class BuildCanceller(object): def __init__(self, app=None): self.build_manager_config = app.config.get('BUILD_MANAGER') if ((app is None) or (self.build_manager_config is None)): self.handler = NoopCanceller() else: self.handler = None def try_cancel_build(self, uuid): if (self.handler is None): canceller = CANCELLERS.get(self.build_manager_config[0], NoopCanceller) self.handler = canceller(self.build_manager_config[1]) return self.handler.try_cancel_build(uuid)
def test_basic(): with pm.Model(coords={'test_dim': range(3)}) as m_old: x = pm.Normal('x') y = pm.Deterministic('y', (x + 1)) w = pm.HalfNormal('w', pm.math.exp(y)) z = pm.Normal('z', y, w, observed=[0, 1, 2], dims=('test_dim',)) pot = pm.Potential('pot', (x * 2)) (m_fgraph, memo) = fgraph_from_model(m_old) assert isinstance(m_fgraph, FunctionGraph) assert isinstance(memo[x].owner.op, ModelFreeRV) assert isinstance(memo[y].owner.op, ModelDeterministic) assert isinstance(memo[w].owner.op, ModelFreeRV) assert isinstance(memo[z].owner.op, ModelObservedRV) assert isinstance(memo[pot].owner.op, ModelPotential) m_new = model_from_fgraph(m_fgraph) assert isinstance(m_new, pm.Model) assert (m_new.coords == {'test_dim': tuple(range(3))}) assert (m_new._dim_lengths['test_dim'].eval() == 3) assert (m_new.named_vars_to_dims == {'z': ['test_dim']}) named_vars = {'x', 'y', 'w', 'z', 'pot'} assert (set(m_new.named_vars) == named_vars) for named_var in named_vars: assert (m_new[named_var] is not m_old[named_var]) for (value_new, value_old) in zip(m_new.rvs_to_values.values(), m_old.rvs_to_values.values()): if (not isinstance(value_new, Constant)): assert (value_new is not value_old) assert (m_new['x'] in m_new.free_RVs) assert (m_new['w'] in m_new.free_RVs) assert (m_new['y'] in m_new.deterministics) assert (m_new['z'] in m_new.observed_RVs) assert (m_new['pot'] in m_new.potentials) assert (m_new.rvs_to_transforms[m_new['x']] is None) assert (m_new.rvs_to_transforms[m_new['w']] is pm.distributions.transforms.log) assert (m_new.rvs_to_transforms[m_new['z']] is None) (new_y_draw, new_z_draw) = pm.draw([m_new['y'], m_new['z']], draws=5, random_seed=1) (old_y_draw, old_z_draw) = pm.draw([m_old['y'], m_old['z']], draws=5, random_seed=1) np.testing.assert_array_equal(new_y_draw, old_y_draw) np.testing.assert_array_equal(new_z_draw, old_z_draw) ip = m_new.initial_point() np.testing.assert_equal(m_new.compile_logp()(ip), m_old.compile_logp()(ip))
def upload_to_server(errors: List[NamedTuple], paths: List[str], config: Dict[(str, str)], url: str, version: str) -> None: unique_id = get_hashed_id() files = [] for path in paths: f = open(path) files.append(f) upload = {str(i): f for (i, f) in enumerate(files)} errors_dict = errors_to_dict(errors) to_json = {'errors': errors_dict} if config: to_json['cfg'] = config payload = json.dumps(to_json) try: response = requests.post(url=url, files=upload, data={'id': unique_id, 'version': version, 'payload': payload}) for f in files: f.close() response.raise_for_status() print('[INFO] Upload successful') except requests.HTTPError as e: print('[ERROR] Upload failed') if (e.response.status_code == 400): print('[ERROR] HTTP Response Status 400: Client-side error, likely due to improper syntax. Please report this to your instructor (and attach the code that caused the error).') elif (e.response.status_code == 403): print('[ERROR] HTTP Response Status 403: Authorization is currently required for submission.') elif (e.response.status_code == 500): print("[ERROR] HTTP Response Status 500: The server ran into a situation it doesn't know how to handle. ") print('Please report this to your instructor (and attach the code that caused the error).') elif (e.response.status_code == 503): print('[ERROR] HTTP Response Status 503: The server is not ready to handle your request. ') print('It may be down for maintenance.') else: print('[ERROR] Error message: "{}"'.format(e)) except requests.ConnectionError as e: print('[ERROR] Upload failed') print('[ERROR] Error message: Connection timed out. This may be caused by your firewall, or the server may be temporarily down.')
def get_model_and_config(model_args: argparse.Namespace): labels = UD_HEAD_LABELS label_map: Dict[(int, str)] = {i: label for (i, label) in enumerate(labels)} num_labels = len(labels) config_kwargs = {'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': (model_args.use_auth_token if model_args.use_auth_token else None)} config = AutoConfig.from_pretrained((model_args.config_name if model_args.config_name else model_args.model_name_or_path), num_labels=num_labels, id2label=label_map, label2id={label: i for (i, label) in enumerate(labels)}, attention_probs_dropout_prob=model_args.dropout_prob, hidden_dropout_prob=model_args.dropout_prob, **config_kwargs) logger.info(f'Using dropout with probability {model_args.dropout_prob}') if (config.model_type in ['vit_mae', 'pixel', 'bert']): config.pad_token_id = (- 100) if (config.model_type in ['vit_mae', 'pixel', 'bert', 'roberta']): model = AutoModelForBiaffineParsing.from_pretrained(model_args.model_name_or_path, config=config, **config_kwargs) else: raise ValueError(f'Model type {config.model_type} not supported.') return (model, config)
def Todo(): (items, set_items) = reactpy.hooks.use_state([]) async def add_new_task(event): if (event['key'] == 'Enter'): set_items([*items, event['target']['value']]) tasks = [] for (index, text) in enumerate(items): async def remove_task(event, index=index): set_items((items[:index] + items[(index + 1):])) task_text = reactpy.html.td(reactpy.html.p(text)) delete_button = reactpy.html.td({'on_click': remove_task}, reactpy.html.button(['x'])) tasks.append(reactpy.html.tr(task_text, delete_button)) task_input = reactpy.html.input({'on_key_down': add_new_task}) task_table = reactpy.html.table(tasks) return reactpy.html.div(reactpy.html.p('press enter to add a task:'), task_input, task_table)
class FC3_Firstboot(KickstartCommand): removedKeywords = KickstartCommand.removedKeywords removedAttrs = KickstartCommand.removedAttrs def __init__(self, writePriority=0, *args, **kwargs): KickstartCommand.__init__(self, writePriority, *args, **kwargs) self.op = self._getParser() self.firstboot = kwargs.get('firstboot', None) def __str__(self): retval = KickstartCommand.__str__(self) if (self.firstboot is None): return retval if (self.firstboot == FIRSTBOOT_SKIP): retval += 'firstboot --disable\n' elif (self.firstboot == FIRSTBOOT_DEFAULT): retval += '# Run the Setup Agent on first boot\nfirstboot --enable\n' elif (self.firstboot == FIRSTBOOT_RECONFIG): retval += '# Run the Setup Agent on first boot\nfirstboot --reconfig\n' return retval def _getParser(self): op = KSOptionParser(prog='firstboot', description='\n Determine whether the Setup Agent starts the first\n time the system is booted. If enabled, the\n ``initial-setup`` package must be installed. If not\n specified, the setup agent (initial-setup) is disabled\n by default.', version=FC3) op.add_argument('--disable', '--disabled', dest='firstboot', action='store_const', const=FIRSTBOOT_SKIP, version=FC3, help='The Setup Agent is not started the first time the\n system boots.') op.add_argument('--enable', '--enabled', dest='firstboot', action='store_const', const=FIRSTBOOT_DEFAULT, version=FC3, help='The Setup Agent is started the first time the\n system boots.') op.add_argument('--reconfig', dest='firstboot', version=FC3, action='store_const', const=FIRSTBOOT_RECONFIG, help='\n Enable the Setup Agent to start at boot time in\n reconfiguration mode. This mode enables the language,\n mouse, keyboard, root password, security level,\n time zone, and networking configuration options in\n addition to the default ones.') return op def parse(self, args): ns = self.op.parse_args(args=args, lineno=self.lineno) self.firstboot = ns.firstboot return self
def test_create_args(tmp_path, capfd): if (utils.platform != 'linux'): pytest.skip('the test is only relevant to the linux build') project_dir = (tmp_path / 'project') basic_project.generate(project_dir) actual_wheels = utils.cibuildwheel_run(project_dir, add_env={'CIBW_BUILD': 'cp310-manylinux_*', 'CIBW_BEFORE_ALL': 'echo TEST_CREATE_ARGS is set to $TEST_CREATE_ARGS', 'CIBW_CONTAINER_ENGINE': 'docker; create_args: --env=TEST_CREATE_ARGS=itworks'}) expected_wheels = [w for w in utils.expected_wheels('spam', '0.1.0') if ('cp310-manylinux' in w)] assert (set(actual_wheels) == set(expected_wheels)) captured = capfd.readouterr() assert ('TEST_CREATE_ARGS is set to itworks' in captured.out)
class CategoricalConvPolicy(StochasticPolicy, LayersPowered, Serializable): def __init__(self, name, env_spec, conv_filters, conv_filter_sizes, conv_strides, conv_pads, hidden_sizes=[], hidden_nonlinearity=tf.nn.relu, output_nonlinearity=tf.nn.softmax, prob_network=None): Serializable.quick_init(self, locals()) assert isinstance(env_spec.action_space, Discrete) self._env_spec = env_spec if (prob_network is None): prob_network = ConvNetwork(input_shape=env_spec.observation_space.shape, output_dim=env_spec.action_space.n, conv_filters=conv_filters, conv_filter_sizes=conv_filter_sizes, conv_strides=conv_strides, conv_pads=conv_pads, hidden_sizes=hidden_sizes, hidden_nonlinearity=hidden_nonlinearity, output_nonlinearity=output_nonlinearity, name='prob_network') self._l_prob = prob_network.output_layer self._l_obs = prob_network.input_layer self._f_prob = tensor_utils.compile_function([prob_network.input_layer.input_var], L.get_output(prob_network.output_layer)) self._dist = Categorical(env_spec.action_space.n) super(CategoricalConvPolicy, self).__init__(env_spec) LayersPowered.__init__(self, [prob_network.output_layer]) def vectorized(self): return True def dist_info_sym(self, obs_var, state_info_vars=None): return dict(prob=L.get_output(self._l_prob, {self._l_obs: tf.cast(obs_var, tf.float32)})) def dist_info(self, obs, state_infos=None): return dict(prob=self._f_prob(obs)) def get_action(self, observation): flat_obs = self.observation_space.flatten(observation) prob = self._f_prob([flat_obs])[0] action = self.action_space.weighted_sample(prob) return (action, dict(prob=prob)) def get_actions(self, observations): flat_obs = self.observation_space.flatten_n(observations) probs = self._f_prob(flat_obs) actions = list(map(self.action_space.weighted_sample, probs)) return (actions, dict(prob=probs)) def distribution(self): return self._dist
def initialize_filterbank(sample_rate, n_harmonic, semitone_scale): low_midi = note_to_midi('C1') high_note = hz_to_note((sample_rate / (2 * n_harmonic))) high_midi = note_to_midi(high_note) level = ((high_midi - low_midi) * semitone_scale) midi = np.linspace(low_midi, high_midi, (level + 1)) hz = midi_to_hz(midi[:(- 1)]) harmonic_hz = [] for i in range(n_harmonic): harmonic_hz = np.concatenate((harmonic_hz, (hz * (i + 1)))) return (harmonic_hz, level)
class PostgresExplainLexer(RegexLexer): name = 'PostgreSQL EXPLAIN dialect' aliases = ['postgres-explain'] filenames = ['*.explain'] mimetypes = ['text/x-postgresql-explain'] url = ' version_added = '2.15' tokens = {'root': [('(:|\\(|\\)|ms|kB|->|\\.\\.|\\,)', Punctuation), ('(\\s+)', Whitespace), ('(cost)(=?)', bygroups(Name.Class, Punctuation), 'instrumentation'), ('(actual)( )(=?)', bygroups(Name.Class, Whitespace, Punctuation), 'instrumentation'), (words(('actual', 'Memory Usage', 'Memory', 'Buckets', 'Batches', 'originally', 'row', 'rows', 'Hits', 'Misses', 'Evictions', 'Overflows'), suffix='\\b'), Comment.Single), ('(hit|read|dirtied|written|write|time|calls)(=)', bygroups(Comment.Single, Operator)), ('(shared|temp|local)', Keyword.Pseudo), ('(Sort Method)(: )', bygroups(Comment.Preproc, Punctuation), 'sort'), ('(Sort Key|Group Key|Presorted Key|Hash Key)(:)( )', bygroups(Comment.Preproc, Punctuation, Whitespace), 'object_name'), ('(Cache Key|Cache Mode)(:)( )', bygroups(Comment, Punctuation, Whitespace), 'object_name'), (words(('Join Filter', 'Subplans Removed', 'Filter', 'Merge Cond', 'Hash Cond', 'Index Cond', 'Recheck Cond', 'Heap Blocks', 'TID Cond', 'Run Condition', 'Order By', 'Function Call', 'Table Function Call', 'Inner Unique', 'Params Evaluated', 'Single Copy', 'Sampling', 'One-Time Filter', 'Output', 'Relations', 'Remote SQL'), suffix='\\b'), Comment.Preproc, 'predicate'), ('Conflict ', Comment.Preproc, 'conflict'), ('(InitPlan|SubPlan)( )(\\d+)( )', bygroups(Keyword, Whitespace, Number.Integer, Whitespace), 'init_plan'), (words(('Sort Method', 'Join Filter', 'Planning time', 'Planning Time', 'Execution time', 'Execution Time', 'Workers Planned', 'Workers Launched', 'Buffers', 'Planning', 'Worker', 'Query Identifier', 'Time', 'Full-sort Groups', 'Pre-sorted Groups'), suffix='\\b'), Comment.Preproc), (words(('Rows Removed by Join Filter', 'Rows Removed by Filter', 'Rows Removed by Index Recheck', 'Heap Fetches', 'never executed'), suffix='\\b'), Name.Exception), ('(I/O Timings)(:)( )', bygroups(Name.Exception, Punctuation, Whitespace)), (words(EXPLAIN_KEYWORDS, suffix='\\b'), Keyword), ('((Right|Left|Full|Semi|Anti) Join)', Keyword.Type), ('(Parallel |Async |Finalize |Partial )', Comment.Preproc), ('Backward', Comment.Preproc), ('(Intersect|Except|Hash)', Comment.Preproc), ('(CTE)( )(\\w*)?', bygroups(Comment, Whitespace, Name.Variable)), ('(on|using)', Punctuation, 'object_name'), ("'(''|[^'])*'", String.Single), ('-?\\d+\\.\\d+', Number.Float), ('(-?\\d+)', Number.Integer), ('(true|false)', Name.Constant), ('\\s*QUERY PLAN\\s*\\n\\s*-+', Comment.Single), ('(Settings)(:)( )', bygroups(Comment.Preproc, Punctuation, Whitespace), 'setting'), ('(JIT|Functions|Options|Timing)(:)', bygroups(Comment.Preproc, Punctuation)), ('(Inlining|Optimization|Expressions|Deforming|Generation|Emission|Total)', Keyword.Pseudo), ('(Trigger)( )(\\S*)(:)( )', bygroups(Comment.Preproc, Whitespace, Name.Variable, Punctuation, Whitespace))], 'expression': [('\\(', Punctuation, '#push'), ('\\)', Punctuation, '#pop'), ('(never executed)', Name.Exception), ('[^)(]+', Comment)], 'object_name': [('(\\(cost)(=?)', bygroups(Name.Class, Punctuation), 'instrumentation'), ('(\\(actual)( )(=?)', bygroups(Name.Class, Whitespace, Punctuation), 'instrumentation'), ('\\(', Punctuation, 'expression'), ('(on)', Punctuation), ('\\w+(\\.\\w+)*( USING \\S+| \\w+ USING \\S+)', Name.Variable), ('\\"?\\w+\\"?(?:\\.\\"?\\w+\\"?)?', Name.Variable), ("\\'\\S*\\'", Name.Variable), (',\\n', Punctuation, 'object_name'), (',', Punctuation, 'object_name'), ('"\\*SELECT\\*( \\d+)?"(.\\w+)?', Name.Variable), ('"\\*VALUES\\*(_\\d+)?"(.\\w+)?', Name.Variable), ('"ANY_subquery"', Name.Variable), ('\\$\\d+', Name.Variable), ('::\\w+', Name.Variable), (' +', Whitespace), ('"', Punctuation), ('\\[\\.\\.\\.\\]', Punctuation), ('\\)', Punctuation, '#pop')], 'predicate': [('(\\()([^\\n]*)(\\))', bygroups(Punctuation, Name.Variable, Punctuation), '#pop'), ('[^\\n]*', Name.Variable, '#pop')], 'instrumentation': [('=|\\.\\.', Punctuation), (' +', Whitespace), ('(rows|width|time|loops)', Name.Class), ('\\d+\\.\\d+', Number.Float), ('(\\d+)', Number.Integer), ('\\)', Punctuation, '#pop')], 'conflict': [('(Resolution: )(\\w+)', bygroups(Comment.Preproc, Name.Variable)), ('(Arbiter \\w+:)', Comment.Preproc, 'object_name'), ('(Filter: )', Comment.Preproc, 'predicate')], 'setting': [("([a-z_]*?)(\\s*)(=)(\\s*)(\\'.*?\\')", bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String)), ('\\, ', Punctuation)], 'init_plan': [('\\(', Punctuation), ('returns \\$\\d+(,\\$\\d+)?', Name.Variable), ('\\)', Punctuation, '#pop')], 'sort': [(':|kB', Punctuation), ('(quicksort|top-N|heapsort|Average|Memory|Peak)', Comment.Prepoc), ('(external|merge|Disk|sort)', Name.Exception), ('(\\d+)', Number.Integer), (' +', Whitespace)]}
def train_translation_model(data_dir, arch, extra_flags=None, task='translation', run_validation=False): train_parser = options.get_training_parser() train_args = options.parse_args_and_arch(train_parser, (['--task', task, data_dir, '--save-dir', data_dir, '--arch', arch, '--lr', '0.05', '--max-tokens', '500', '--max-epoch', '1', '--no-progress-bar', '--distributed-world-size', '1', '--source-lang', 'in', '--target-lang', 'out'] + (extra_flags or []))) train.main(train_args) if run_validation: validate_parser = options.get_validation_parser() validate_args = options.parse_args_and_arch(validate_parser, ['--task', task, data_dir, '--path', os.path.join(data_dir, 'checkpoint_last.pt'), '--valid-subset', 'valid', '--max-tokens', '500', '--no-progress-bar']) validate.main(validate_args)
class MultiHeadedDotAttention(nn.Module): def __init__(self, h, d_model, dropout=0.1, scale=1, project_k_v=1, use_output_layer=1, do_aoa=0, norm_q=0, dropout_aoa=0.3): super(MultiHeadedDotAttention, self).__init__() assert (((d_model * scale) % h) == 0) self.d_k = ((d_model * scale) // h) self.h = h self.batch_info = [] self.att_layer_idx = 0 self.project_k_v = project_k_v if norm_q: self.norm = LayerNorm(d_model) else: self.norm = (lambda x: x) self.q_linears = nn.Linear(d_model, (d_model * scale)) self.k_linears = clones(nn.Linear(d_model, (d_model * scale)), 3) self.v_linears = clones(nn.Linear(d_model, (d_model * scale)), 3) self.output_layer = nn.Linear((d_model * scale), d_model) self.use_aoa = do_aoa if self.use_aoa: self.aoa_layer = nn.Sequential(nn.Linear(((1 + scale) * d_model), (2 * d_model)), nn.GLU()) if (dropout_aoa > 0): self.dropout_aoa = nn.Dropout(p=dropout_aoa) else: self.dropout_aoa = (lambda x: x) if (self.use_aoa or (not use_output_layer)): del self.output_layer self.output_layer = (lambda x: x) self.attn = None self.dropout = nn.Dropout(p=dropout) def forward(self, query, value, key, flag, mask=None): if (mask is not None): if (len(mask.size()) == 2): mask = mask.unsqueeze((- 2)) mask = mask.unsqueeze(1) single_query = 0 if (len(query.size()) == 2): single_query = 1 query = query.unsqueeze(1) nbatches = query.size(0) query = self.norm(query) if (self.project_k_v == 0): query_ = self.linears[0](query).view(nbatches, (- 1), self.h, self.d_k).transpose(1, 2) key_ = key.view(nbatches, (- 1), self.h, self.d_k).transpose(1, 2) value_ = value.view(nbatches, (- 1), self.h, self.d_k).transpose(1, 2) else: query_ = self.q_linears(query).view(nbatches, (- 1), self.h, self.d_k).transpose(1, 2) (key_p, key_n, key_c) = [l(x).view(nbatches, (- 1), self.h, self.d_k).transpose(1, 2) for (l, x) in zip(self.k_linears, (key, key, key))] (value_p, value_n, value_c) = [l(x).view(nbatches, (- 1), self.h, self.d_k).transpose(1, 2) for (l, x) in zip(self.v_linears, (value, value, value))] (x, self.attn, p_attn2, p_attn3) = attention(query_, key_p, key_n, key_c, value_p, value_n, value_c, flag, mask=mask, dropout=self.dropout) x = x.transpose(1, 2).contiguous().view(nbatches, (- 1), (self.h * self.d_k)) if self.use_aoa: x = self.aoa_layer(self.dropout_aoa(torch.cat([x, query], (- 1)))) x = self.output_layer(x) if single_query: query = query.squeeze(1) x = x.squeeze(1) return x
def test_get_executable(tmpfolder): assert (shell.get_executable('python') is not None) assert (shell.get_executable('python', tmpfolder, include_path=False) is None) python = Path(sys.executable).resolve() bin_path = shell.get_executable('python', include_path=False, prefix=sys.prefix) bin_path = Path(bin_path).resolve() assert (bin_path.stem in python.stem) assert (bin_path.parent == python.parent) assert (shell.get_executable(uniqstr()) is None)
def test_trajectory_reader(tmpdir): tmpcatalog = os.path.join(tmpdir, 'my_catalog.xosc') cf = xosc.CatalogFile() cf.create_catalog(tmpcatalog, 'TrajectoryCatalog', 'My first miscobject catalog', 'Mandolin') orig = xosc.Trajectory('my_trajectory', False) orig.add_shape(xosc.Clothoid(0.1, 0.01, 100, xosc.WorldPosition())) cf.add_to_catalog(orig) cf.dump() read = xosc.CatalogReader(xosc.CatalogReference('my_catalog', 'my_trajectory'), tmpdir) assert (read == orig)
class SingularityLexer(RegexLexer): name = 'Singularity' url = ' aliases = ['singularity'] filenames = ['*.def', 'Singularity'] version_added = '2.6' flags = ((re.IGNORECASE | re.MULTILINE) | re.DOTALL) _headers = '^(\\s*)(bootstrap|from|osversion|mirrorurl|include|registry|namespace|includecmd)(:)' _section = '^(%(?:pre|post|setup|environment|help|labels|test|runscript|files|startscript))(\\s*)' _appsect = '^(%app(?:install|help|run|labels|env|test|files))(\\s*)' tokens = {'root': [(_section, bygroups(Generic.Heading, Whitespace), 'script'), (_appsect, bygroups(Generic.Heading, Whitespace), 'script'), (_headers, bygroups(Whitespace, Keyword, Text)), ('\\s*#.*?\\n', Comment), ('\\b(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))\\b', Number), ('[ \\t]+', Whitespace), ('(?!^\\s*%).', Text)], 'script': [('(.+?(?=^\\s*%))|(.*)', using(BashLexer), '#pop')]} def analyse_text(text): result = 0 if re.search('\\b(?:osversion|includecmd|mirrorurl)\\b', text, re.IGNORECASE): result += 0.5 if re.search(SingularityLexer._section[1:], text): result += 0.49 return result
def print_all_threads(): global _state assert _state, "Global variable '_state' not set" for thread_state in _state.values(): print_thread_profile(thread_state) print() print('total - time spent to execute the function') print('inline - time spent in the function itself') print('sleep - time waiting in a greenlet.switch') print() print('total and inline do not include sleep') print('total include subcalls while inline does not')
def perm_test_across_days(animal_day_transmats, animal_id, from_state, transition, n_perm=1000, alpha=0.05): day_transmats_map = animal_day_transmats[animal_id] days = list(day_transmats_map.keys()) pairs = permutations(days, 2) condition_counter_map = {pair: (day_transmats_map[pair[0]].counts, day_transmats_map[pair[1]].counts) for pair in pairs} return _multiple_perm_tests(condition_counter_map, from_state, transition, n_perm=n_perm, alpha=alpha)
def get_images_tc(paths, labels, nb_samples=None, shuffle=True, is_val=False): if (nb_samples is not None): sampler = (lambda x: random.sample(x, nb_samples)) else: sampler = (lambda x: x) if (is_val is False): images = [(i, os.path.join(path, image)) for (i, path) in zip(labels, paths) for image in sampler(os.listdir(path)[0:500])] else: images = [(i, os.path.join(path, image)) for (i, path) in zip(labels, paths) for image in sampler(os.listdir(path)[500:])] if shuffle: random.shuffle(images) return images
class DeltaFile(LikeFile): def __init__(self, signature, new_file): LikeFile.__init__(self, new_file) if (type(signature) is bytes): sig_string = signature else: self._check_file(signature) sig_string = signature.read() signature.close() try: self.maker = _librsync.new_deltamaker(sig_string) except _librsync.librsyncError as e: raise librsyncError(str(e))
class Bunch(Mapping): def __init__(self, name, data): self._name = str(name) self._data = data def __getitem__(self, k): return self._data[k] def __getattr__(self, a): try: return self._data[a] except KeyError: raise AttributeError(a) def __copy__(self): cls = type(self) return cls(str(self._name), data=self._data) def __deepcopy__(self, memo): cls = type(self) clone = cls(name=str(self._name), data=None) memo[id(self)] = clone clone._data = copy.deepcopy(self._data, memo) return clone def __iter__(self): return iter(self._data) def __len__(self): return len(self._data) def __repr__(self): content = (repr(set(self._data)) if self._data else '{}') return f'<{self._name} {content}>' def __dir__(self): return (super().__dir__() + list(self._data))
.parametrize('entry_point_values_by_group', [{ApplicationPlugin.group: ['FirstApplicationPlugin', 'SecondApplicationPlugin'], Plugin.group: ['FirstPlugin', 'SecondPlugin']}]) def test_show_displays_installed_plugins_with_multiple_plugins(app: PoetryTestApplication, tester: CommandTester) -> None: tester.execute('') expected = '\n - poetry-plugin (1.2.3)\n 2 plugins and 2 application plugins\n' assert (tester.io.fetch_output() == expected)
class TOperonClear(TOperonBase): def test_misc(self): self.check_false(['clear'], False, True) self.check_false(['clear', self.f], False, True) self.check_true(['clear', '-a', self.f], False, False) self.check_false(['-v', 'clear', '-e', self.f], False, True) self.check_true(['-v', 'clear', '-e', 'xx', self.f], False, True) self.check_true(['clear', '-e', 'xx', self.f], False, False) self.check_false(['clear', '-e', 'x', '-a', self.f], False, True) def _test_all(self): self.check(['clear', '-a', self.f], True, output=False) self.s.reload() self.assertFalse(self.s.realkeys()) self.check(['clear', '-a', self.f, self.f], True, output=False) def _test_all_dry_run(self): old_len = len(self.s.realkeys()) self.assertTrue(old_len) self.check(['clear', '-a', '--dry-run', self.f], True) self.s.reload() self.assertEqual(len(self.s.realkeys()), old_len) def _test_pattern(self): old_len = len(self.s.realkeys()) self.check(['clear', '-e', 'a.*', self.f], True, output=False) self.s.reload() self.assertEqual(len(self.s.realkeys()), (old_len - 2)) def _test_simple(self): old_len = len(self.s.realkeys()) self.check(['clear', 'a.*', self.f], True, output=False) self.s.reload() self.assertEqual(len(self.s.realkeys()), old_len) self.check(['clear', '--dry-run', 'artist', self.f], True) self.s.reload() self.assertEqual(len(self.s.realkeys()), old_len) self.check(['clear', 'artist', self.f], True, output=False) self.s.reload() self.assertEqual(len(self.s.realkeys()), (old_len - 1))
class PointnetSAModuleMSG(_PointnetSAModuleBase): def __init__(self, *, npoint: int, radii: List[float], nsamples: List[int], mlps: List[List[int]], bn: bool=True, use_xyz: bool=True, pool_method='max_pool'): super().__init__() assert (len(radii) == len(nsamples) == len(mlps)) self.npoint = npoint self.groupers = nn.ModuleList() self.mlps = nn.ModuleList() for i in range(len(radii)): radius = radii[i] nsample = nsamples[i] self.groupers.append((pointnet2_utils.QueryAndGroup(radius, nsample, use_xyz=use_xyz) if (npoint is not None) else pointnet2_utils.GroupAll(use_xyz))) mlp_spec = mlps[i] if use_xyz: mlp_spec[0] += 3 shared_mlps = [] for k in range((len(mlp_spec) - 1)): shared_mlps.extend([nn.Conv2d(mlp_spec[k], mlp_spec[(k + 1)], kernel_size=1, bias=False), nn.BatchNorm2d(mlp_spec[(k + 1)]), nn.ReLU()]) self.mlps.append(nn.Sequential(*shared_mlps)) self.pool_method = pool_method
def generate_diverse_samples(cfg): sample_directory = create_sample_directory(cfg) path = get_model_path(cfg.image_name, cfg.run_name) model = Diffusion.load_from_checkpoint(path, model=NextNet(depth=cfg.network_depth), timesteps=cfg.diffusion_timesteps, training_target='x0', noise_schedule='linear').cuda() if (cfg.sample_size is None): size = tuple(imread(f'./images/{cfg.image_name}').shape[(- 2):]) else: size = two_tuple(cfg.sample_size) batch_size = 8 samples = [] for i in tqdm(range(0, cfg.sample_count, batch_size)): samples.append(model.sample(image_size=size, batch_size=min(batch_size, (cfg.sample_count - i)))) samples = torch.cat(samples, dim=0) save_diffusion_sample(samples, os.path.join(sample_directory, 'sample.png'))
def get_args(): parser = argparse.ArgumentParser(description='process the textgrid files') parser.add_argument('--path', type=str, required=True, help='Data path') parser.add_argument('--max_length', default=100000, type=float, help='overlap speech max time,if longger than max length should cut') parser.add_argument('--overlap_length', default=1, type=float, help='if length longer than max length, speech overlength shorter, is cut') args = parser.parse_args() return args
def test_update_sections(db, settings): xml_file = (((Path(settings.BASE_DIR) / 'xml') / 'elements') / 'sections.xml') root = read_xml_file(xml_file) version = root.attrib.get('version') elements = flat_xml_to_elements(root) elements = convert_elements(elements, version) elements = order_elements(elements) elements = elements.values() import_elements(elements) assert (len(root) == len(elements) == 146) assert all(((element['created'] is False) for element in elements)) assert all(((element['updated'] is True) for element in elements))
class DreamBoothDataset(Dataset): def __init__(self, concepts_list, tokenizer, with_prior_preservation=True, size=512, center_crop=False, num_class_images=None, pad_tokens=False, hflip=False): self.size = size self.center_crop = center_crop self.tokenizer = tokenizer self.with_prior_preservation = with_prior_preservation self.pad_tokens = pad_tokens self.instance_images_path = [] self.class_images_path = [] for concept in concepts_list: inst_img_path = [(x, concept['instance_prompt']) for x in Path(concept['instance_data_dir']).iterdir() if x.is_file()] self.instance_images_path.extend(inst_img_path) if with_prior_preservation: class_img_path = [(x, concept['class_prompt']) for x in Path(concept['class_data_dir']).iterdir() if x.is_file()] self.class_images_path.extend(class_img_path[:num_class_images]) random.shuffle(self.instance_images_path) self.num_instance_images = len(self.instance_images_path) self.num_class_images = len(self.class_images_path) self._length = max(self.num_class_images, self.num_instance_images) self.image_transforms = transforms.Compose([transforms.RandomHorizontalFlip((0.5 * hflip)), transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR), (transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]) def __len__(self): return self._length def __getitem__(self, index): example = {} (instance_path, instance_prompt) = self.instance_images_path[(index % self.num_instance_images)] instance_image = Image.open(instance_path) if (not (instance_image.mode == 'RGB')): instance_image = instance_image.convert('RGB') example['instance_images'] = self.image_transforms(instance_image) example['instance_prompt_ids'] = self.tokenizer(instance_prompt, padding=('max_length' if self.pad_tokens else 'do_not_pad'), truncation=True, max_length=self.tokenizer.model_max_length).input_ids if self.with_prior_preservation: (class_path, class_prompt) = self.class_images_path[(index % self.num_class_images)] class_image = Image.open(class_path) if (not (class_image.mode == 'RGB')): class_image = class_image.convert('RGB') example['class_images'] = self.image_transforms(class_image) example['class_prompt_ids'] = self.tokenizer(class_prompt, padding=('max_length' if self.pad_tokens else 'do_not_pad'), truncation=True, max_length=self.tokenizer.model_max_length).input_ids return example