code
stringlengths
17
6.64M
class TestNorms(unittest.TestCase): def test_norm(self): def f(t, x): return x t = torch.tensor([0.0, 1.0]) is_called = False def norm(state): nonlocal is_called is_called = True self.assertIsInstance(state, torch.Tensor) ...
def rel_error(true, estimate): return ((true - estimate) / true).abs().max()
class TestSolverError(unittest.TestCase): def test_odeint(self): for reverse in (False, True): for dtype in DTYPES: for device in DEVICES: for method in METHODS: if ((method in SCIPY_METHODS) and (dtype == torch.complex64)): ...
class TestScipySolvers(unittest.TestCase): def test_odeint(self): for reverse in (False, True): for dtype in DTYPES: for device in DEVICES: for solver in ['RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA']: for ode in PROBLEMS: ...
class TestNoIntegration(unittest.TestCase): def test_odeint(self): for reverse in (False, True): for dtype in DTYPES: for device in DEVICES: for method in METHODS: for ode in PROBLEMS: with self.subTest(re...
class _JumpF(): def __init__(self): self.nfe = 0 def __call__(self, t, x): self.nfe += 1 if (t < 0.5): return ((- 0.5) * x) else: return (x ** 2)
class TestDiscontinuities(unittest.TestCase): def test_odeint_jump_t(self): for adjoint in (False, True): for dtype in DTYPES: for device in DEVICES: for method in ADAPTIVE_METHODS: with self.subTest(adjoint=adjoint, dtype=dtype, dev...
class TestGridConstructor(unittest.TestCase): def test_grid_constructor(self): def f(t, x): return x for adjoint in (False, True): with self.subTest(adjoint=adjoint): x0 = torch.tensor(1.0, requires_grad=True) t = torch.tensor([0.0, 1.0]) ...
class TestMinMaxStep(unittest.TestCase): def test_min_max_step(self): with warnings.catch_warnings(): warnings.simplefilter('ignore') for device in DEVICES: for min_step in (0, 2): for max_step in (float('inf'), 5): for (...
class _NeuralF(torch.nn.Module): def __init__(self, width, oscillate): super(_NeuralF, self).__init__() self.linears = torch.nn.Sequential(torch.nn.Linear(2, width), torch.nn.Tanh(), torch.nn.Linear(width, 2), torch.nn.Tanh()) self.nfe = 0 self.oscillate = oscillate def forwa...
class TestCallbacks(unittest.TestCase): def test_wrong_callback(self): x0 = torch.tensor([1.0, 2.0]) t = torch.tensor([0.0, 1.0]) for method in FIXED_METHODS: for callback_name in ('callback_accept_step', 'callback_reject_step'): with self.subTest(method=method...
class ConstantODE(torch.nn.Module): def __init__(self): super(ConstantODE, self).__init__() self.a = torch.nn.Parameter(torch.tensor(0.2)) self.b = torch.nn.Parameter(torch.tensor(3.0)) def forward(self, t, y): return (self.a + ((y - ((self.a * t) + self.b)) ** 5)) def y...
class SineODE(torch.nn.Module): def forward(self, t, y): return (((((2 * y) / t) + ((t ** 4) * torch.sin((2 * t)))) - (t ** 2)) + (4 * (t ** 3))) def y_exact(self, t): return ((((((((- 0.5) * (t ** 4)) * torch.cos((2 * t))) + ((0.5 * (t ** 3)) * torch.sin((2 * t)))) + ((0.25 * (t ** 2)) * to...
class LinearODE(torch.nn.Module): def __init__(self, dim=10): super(LinearODE, self).__init__() torch.manual_seed(0) self.dim = dim U = (torch.randn(dim, dim) * 0.1) A = ((2 * U) - (U + U.transpose(0, 1))) self.A = torch.nn.Parameter(A) self.initial_val = n...
def construct_problem(device, npts=10, ode='constant', reverse=False, dtype=torch.float64): f = PROBLEMS[ode]().to(dtype=dtype, device=device) t_points = torch.linspace(1, 8, npts, dtype=torch.float64, device=device, requires_grad=True) sol = f.y_exact(t_points).to(dtype) def _flip(x, dim): i...
class AdaptiveHeunSolver(RKAdaptiveStepsizeODESolver): order = 2 tableau = _ADAPTIVE_HEUN_TABLEAU mid = _AH_C_MID
class OdeintAdjointMethod(torch.autograd.Function): @staticmethod def forward(ctx, shapes, func, y0, t, rtol, atol, method, options, event_fn, adjoint_rtol, adjoint_atol, adjoint_method, adjoint_options, t_requires_grad, *adjoint_params): ctx.shapes = shapes ctx.func = func ctx.adjoin...
def odeint_adjoint(func, y0, t, *, rtol=1e-07, atol=1e-09, method=None, options=None, event_fn=None, adjoint_rtol=None, adjoint_atol=None, adjoint_method=None, adjoint_options=None, adjoint_params=None): if ((adjoint_params is None) and (not isinstance(func, nn.Module))): raise ValueError('func must be an...
def find_parameters(module): assert isinstance(module, nn.Module) if getattr(module, '_is_replica', False): def find_tensor_attributes(module): tuples = [(k, v) for (k, v) in module.__dict__.items() if (torch.is_tensor(v) and v.requires_grad)] return tuples gen = modul...
def handle_adjoint_norm_(adjoint_options, shapes, state_norm): 'In-place modifies the adjoint options to choose or wrap the norm function.' def default_adjoint_norm(tensor_tuple): (t, y, adj_y, *adj_params) = tensor_tuple return max(t.abs(), state_norm(y), state_norm(adj_y), _mixed_norm(adj_p...
class Bosh3Solver(RKAdaptiveStepsizeODESolver): order = 3 tableau = _BOGACKI_SHAMPINE_TABLEAU mid = _BS_C_MID
class Dopri5Solver(RKAdaptiveStepsizeODESolver): order = 5 tableau = _DORMAND_PRINCE_SHAMPINE_TABLEAU mid = DPS_C_MID
class Dopri8Solver(RKAdaptiveStepsizeODESolver): order = 8 tableau = _DOPRI8_TABLEAU mid = _C_mid
def find_event(interp_fn, sign0, t0, t1, event_fn, tol): with torch.no_grad(): nitrs = torch.ceil((torch.log(((t1 - t0) / tol)) / math.log(2.0))) for _ in range(nitrs.long()): t_mid = ((t1 + t0) / 2.0) y_mid = interp_fn(t_mid) sign_mid = torch.sign(event_fn(t_mi...
def combine_event_functions(event_fn, t0, y0): '\n We ensure all event functions are initially positive,\n so then we can combine them by taking a min.\n ' with torch.no_grad(): initial_signs = torch.sign(event_fn(t0, y0)) def combined_event_fn(t, y): c = event_fn(t, y) r...
class Fehlberg2(RKAdaptiveStepsizeODESolver): order = 2 tableau = _FEHLBERG2_TABLEAU mid = _FE_C_MID
def _dot_product(x, y): return sum(((xi * yi) for (xi, yi) in zip(x, y)))
class AdamsBashforthMoulton(FixedGridODESolver): order = 4 def __init__(self, func, y0, rtol=0.001, atol=0.0001, implicit=True, max_iters=_MAX_ITERS, max_order=_MAX_ORDER, **kwargs): super(AdamsBashforthMoulton, self).__init__(func, y0, rtol=rtol, atol=rtol, **kwargs) assert (max_order <= _MA...
class AdamsBashforth(AdamsBashforthMoulton): def __init__(self, func, y0, **kwargs): super(AdamsBashforth, self).__init__(func, y0, implicit=False, **kwargs)
class Euler(FixedGridODESolver): order = 1 def _step_func(self, func, t0, dt, t1, y0): f0 = func(t0, y0, perturb=(Perturb.NEXT if self.perturb else Perturb.NONE)) return ((dt * f0), f0)
class Midpoint(FixedGridODESolver): order = 2 def _step_func(self, func, t0, dt, t1, y0): half_dt = (0.5 * dt) f0 = func(t0, y0, perturb=(Perturb.NEXT if self.perturb else Perturb.NONE)) y_mid = (y0 + (f0 * half_dt)) return ((dt * func((t0 + half_dt), y_mid)), f0)
class RK4(FixedGridODESolver): order = 4 def _step_func(self, func, t0, dt, t1, y0): f0 = func(t0, y0, perturb=(Perturb.NEXT if self.perturb else Perturb.NONE)) return (rk4_alt_step_func(func, t0, dt, t1, y0, f0=f0, perturb=self.perturb), f0)
class Heun3(FixedGridODESolver): order = 3 def _step_func(self, func, t0, dt, t1, y0): f0 = func(t0, y0, perturb=(Perturb.NEXT if self.perturb else Perturb.NONE)) butcher_tableu = [[0.0, 0.0, 0.0, 0.0], [(1 / 3), (1 / 3), 0.0, 0.0], [(2 / 3), 0.0, (2 / 3), 0.0], [0.0, (1 / 4), 0.0, (3 / 4)]] ...
def _interp_fit(y0, y1, y_mid, f0, f1, dt): 'Fit coefficients for 4th order polynomial interpolation.\n\n Args:\n y0: function value at the start of the interval.\n y1: function value at the end of the interval.\n y_mid: function value at the mid-point of the interval.\n f0: derivat...
def _interp_evaluate(coefficients, t0, t1, t): 'Evaluate polynomial interpolation at the given time point.\n\n Args:\n coefficients: list of Tensor coefficients as created by `interp_fit`.\n t0: scalar float64 Tensor giving the start of the interval.\n t1: scalar float64 Tensor giving the ...
def odeint(func, y0, t, *, rtol=1e-07, atol=1e-09, method=None, options=None, event_fn=None): 'Integrate a system of ordinary differential equations.\n\n Solves the initial value problem for a non-stiff system of first order ODEs:\n ```\n dy/dt = func(t, y), y(t[0]) = y0\n ```\n where y...
def odeint_dense(func, y0, t0, t1, *, rtol=1e-07, atol=1e-09, method=None, options=None): assert torch.is_tensor(y0) t = torch.tensor([t0, t1]).to(t0) (shapes, func, y0, t, rtol, atol, method, options, _, _) = _check_inputs(func, y0, t, rtol, atol, method, options, None, SOLVERS) assert (method == 'do...
def odeint_event(func, y0, t0, *, event_fn, reverse_time=False, odeint_interface=odeint, **kwargs): 'Automatically links up the gradient from the event time.' if reverse_time: t = torch.cat([t0.reshape((- 1)), (t0.reshape((- 1)).detach() - 1.0)]) else: t = torch.cat([t0.reshape((- 1)), (t0...
class ImplicitFnGradientRerouting(torch.autograd.Function): @staticmethod def forward(ctx, func, event_fn, event_t, state_t): ' event_t is the solution to event_fn ' ctx.func = func ctx.event_fn = event_fn ctx.save_for_backward(event_t, state_t) return (event_t.detach(...
class ScipyWrapperODESolver(metaclass=abc.ABCMeta): def __init__(self, func, y0, rtol, atol, min_step=0, max_step=float('inf'), solver='LSODA', **unused_kwargs): unused_kwargs.pop('norm', None) unused_kwargs.pop('grid_points', None) unused_kwargs.pop('eps', None) _handle_unused_kw...
def convert_func_to_numpy(func, shape, device, dtype): def np_func(t, y): t = torch.tensor(t).to(device, dtype) y = torch.reshape(torch.tensor(y).to(device, dtype), shape) with torch.no_grad(): f = func(t, y) return f.detach().cpu().numpy().reshape((- 1)) return np...
class AdaptiveStepsizeODESolver(metaclass=abc.ABCMeta): def __init__(self, dtype, y0, norm, **unused_kwargs): _handle_unused_kwargs(self, unused_kwargs) del unused_kwargs self.y0 = y0 self.dtype = dtype self.norm = norm def _before_integrate(self, t): pass ...
class AdaptiveStepsizeEventODESolver(AdaptiveStepsizeODESolver, metaclass=abc.ABCMeta): @abc.abstractmethod def _advance_until_event(self, event_fn): raise NotImplementedError def integrate_until_event(self, t0, event_fn): t0 = t0.to(self.y0.device, self.dtype) self._before_integ...
class FixedGridODESolver(metaclass=abc.ABCMeta): order: int def __init__(self, func, y0, step_size=None, grid_constructor=None, interp='linear', perturb=False, **unused_kwargs): self.atol = unused_kwargs.pop('atol') unused_kwargs.pop('rtol', None) unused_kwargs.pop('norm', None) ...
def bohrToMeters(value, dimension=1): BOHR_CONSTANT = 5.2917725e-11 return (value * (BOHR_CONSTANT ** dimension))
def fileExists(filename): chk = os.path.exists(filename) return chk
class ParseError(Exception): def __init__(self, message, errorTags): Exception.__init__(self, message) self.errorTags = errorTags
def parse_win_mp_grid(f): parse_line_list = (lambda line, delimiter, T: [T(y) for y in [x.strip() for x in line.strip().split(delimiter)] if y]) for line in f.readlines(): if ('mp_grid' in line): return parse_line_list(line.split(':')[1], ' ', int)
def parse_nnkp_nnkpts(f): nnkpts = [] with f as input_data: for line in input_data: if (line.strip() == 'begin nnkpts'): break for line in input_data: if (line.strip() == 'end nnkpts'): break line1 = line.strip() l...
def parse_pair_info_line(line): 'Converts a pair-info line into k1, k2, and a G vector\n ' k1 = float(line[0:8]) k2 = float(line[9:16]) G = (float(line[17:24]), float(line[25:32]), float(line[33:40])) return (k1, k2, G)
def parse_matrix_element_line(line): 'Converts a matrix element line into a value\n ' real_part = float(line[0:18]) imaginary_part = float(line[19:36]) return (real_part + (imaginary_part * 1j))
def parse_mmn_info_line(line): n_energy = int(line[0:12]) n_pairs = int(line[13:24]) n_neighbours = int(line[25:36]) return (n_energy, n_pairs, n_neighbours)
def determine_neighbours(D, d, P=[0, 1, 2]): "Computes a bidirectional graph of points who are adjacent in the\n grid of dimensions `D', in the forward direction given by `d'.\n\n The value at each node in the graph is a tuple containing the\n linear index of the neighbour in the direction `d' a...
def print_usage(): print('Usage: mmn2pathphase case [direction] [-w]') print(' direction x, y, or z; for <x, y, z> (default x)') print(' -w option is for Weyl k-path calculation')
def main(args): VERBOSE = False parse_line_list = (lambda line, delimiter, T: [T(y) for y in [x.strip() for x in line.strip().split(delimiter)] if y]) if (len(args) < 2): print('Error: no case or direction provided') exit(1) spOption = '' wCalc = False for arg in args: ...
def rmerror(corename): pattern = (('*' + corename) + '*.error') print(DEFAULT_PREFIX, 'Cleaning error files:', pattern) for errfilename in glob.glob(pattern): os.remove(errfilename)
def getStringFromList(theList): if (len(theList) > 1): theList = functools.reduce((lambda i, j: ((str(i) + ' ') + str(j))), theList) return str(theList) else: return str(theList[0])
class VirtualShellInstance(): def __init__(self, command, *arguments, **options): if arguments: self._arguments = getStringFromList(arguments) else: self._arguments = '' self._command = command self.output = None if ('input' in options): ...
def testerror(corename): pattern = (('*' + corename) + '*.error') for errfilename in glob.glob(pattern): errfilesize = os.path.getsize(errfilename) if (errfilesize != 0): print('ERROR detected in', corename) print('Please check the error file:', errfilename) ...
def WloopIN_Z(X1, X2, S, E): Data = np.append(X1, X2, axis=1) (row, col) = Data.shape ab = np.ones(row) ab.shape = (1, row) Data = np.insert(Data, 2, (S * ab), axis=1) Data = np.insert(Data, 3, X1.T, axis=1) Data = np.insert(Data, 4, X2.T, axis=1) Data = np.insert(Data, 5, (E * ab), ax...
def WloopIN_X(X1, X2, S, E): Data = np.append(X1, X2, axis=1) (row, col) = Data.shape ab = np.ones(row) ab.shape = (1, row) Data = np.insert(Data, 0, (S * ab), axis=1) Data = np.insert(Data, 3, (E * ab), axis=1) Data = np.insert(Data, 4, X1.T, axis=1) Data = np.insert(Data, 5, X2.T, ax...
def WloopIN_Y(X1, X2, S, E): Data = np.append(X1, X2, axis=1) (row, col) = Data.shape ab = np.ones(row) ab.shape = (1, row) Data = np.insert(Data, 1, (S * ab), axis=1) Data = np.insert(Data, 3, X1.T, axis=1) Data = np.insert(Data, 4, (E * ab), axis=1) Data = np.insert(Data, 5, X2.T, ax...
def write_date(f): t = datetime.now() f.write('File written on ') f.write(t.strftime('%d%b%Y at %H:%M:%S')) f.write('\n\n')
def write_calc_only_A(f): f.write('calc_only_A : F\n\n')
def write_real_lattice(f, real_lattice): f.write('begin real_lattice\n') for i in range(3): a = real_lattice[i] f.write(' {0:>11.7f} {1:>11.7f} {2:>11.7f}\n'.format(*a)) f.write('end real_lattice\n\n')
def write_recip_lattice(f, recip_lattice): f.write('begin recip_lattice\n') for i in range(3): a = recip_lattice[i] f.write(' {0:>11.7f} {1:>11.7f} {2:>11.7f}\n'.format(*a)) f.write('end recip_lattice\n\n')
def write_kpoints(f, kpoints): f.write('begin kpoints\n') f.write('{0:>6d}\n'.format(len(kpoints))) for p in kpoints: f.write(' {0:>13.8f} {1:>13.8f} {2:>13.8f}\n'.format(*p)) f.write('end kpoints\n\n')
def write_projections(f): f.write('begin projections\n') f.write('end projections\n\n')
def write_nnkpts(f, nnkpts, wCalc): neighbours_per_kpoint = 3 f.write('begin nnkpts\n') if wCalc: f.write('{0:4d}\n'.format(1)) else: f.write('{0:4d}\n'.format(neighbours_per_kpoint)) for p in nnkpts: f.write(' {0:5d} {1:5d} {2:3d} {3:3d} {4:3d}\n'.format(*p)) f.writ...
def write_exclude_bands(f): f.write('begin exclude_bands\n') f.write('{0:4d}\n'.format(0)) f.write('end exclude_bands\n')
def calculate_nnkpts(D, wCalc, wTranslDir, nkpt): 'Calculates neighbours pairs for all paths. \n D - k-mesh (#,#,#)\n wCalc - Logical var to indicate Weyl path calculation (True/False)\n wTranslDir - Direction for k(1)+G[dir] at the end of the loop.\n nkpt - number of k-points in the l...
def parse_win_kpoints(f): while ('begin kpoints' not in f.readline()): pass kpoints = [] for line in f.readlines(): if ('end kpoints' in line): break kpoint = tuple(parse_line_list(line, ' ', float)) kpoints.append(kpoint) return kpoints
def parse_win_mp_grid(f): for line in f.readlines(): if ('mp_grid' in line): return parse_line_list(line.split(':')[1], ' ', int)
def parse_win_unit_cell_cart(f): reciprocal = (lambda a: numpy.transpose((6.28318 * numpy.linalg.inv(a)))) real_lattice = numpy.zeros(shape=(3, 3)) while ('begin unit_cell_cart' not in f.readline()): pass f.readline() for i in range(3): real_lattice[i] = parse_line_list(f.readline(...
def parse_win(case_name, spinLable): ext = ('.win' + spinLable) file_name = (case_name + ext) f = open(file_name, 'r') (real_lattice, recip_lattice) = parse_win_unit_cell_cart(f) f.close() f = open(file_name, 'r') dimensions = parse_win_mp_grid(f) f.close() f = open(file_name, 'r')...
class InputExample(object): 'A single training/test example for simple sequence classification.' def __init__(self, guid, text_a, text_b=None, label=None): 'Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of t...
class InputFeatures(object): 'A single set of features of data.' def __init__(self, input_ids, input_mask, segment_ids, label_id, valid_ids=None, label_mask=None, ori_label=None, subword=None): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids ...
def readfile(filename, schema='BIO', sep=' '): '\n 数据在txt中格式应该为 \n John B-PER\n Wick I-PER\n say O\n 若schema为IO, 则会强制将B改为I,若为其他,则正常读取\n ' f = open(filename) data = [] sentence = [] label = [] for line in f: if ((len(line) == 0) or line.startswith('-DOCSTART') or (line...
def collect_label_list(data_path, label_type='fine', sep='\t'): f = open(data_path) label_list = [] for line in f: if ((len(line) == 0) or line.startswith('-DOCSTART') or (line[0] == '\n')): continue splits = line.strip().split(sep) if (label_type == 'fine'): ...
class DataProcessor(object): 'Base class for data converters for sequence classification data sets.' def get_examples(self, data_path): 'Gets a collection of `InputExample`s for the train set.' raise NotImplementedError() def get_labels(self): 'Gets the list of labels for this da...
class NerGeneralProcessor(DataProcessor): 'Processor for the general ner data set.' def get_examples(self, data_path, schema='IO', sep=' ', data_type='train', label_type='fine'): return self._create_examples(self._read_file(data_path, schema=schema, sep=sep), data_type) def get_label_map(self, d...
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): 'Loads a data file into a list of `InputBatch`s.' label_map = {label: i for (i, label) in enumerate(label_list, 0)} features = [] for (ex_index, example) in tqdm(enumerate(examples), desc='Examples2Features'): t...
def convert_examples_to_features_lm(examples, label_map, max_seq_length, tokenizer, subword_map): "\n label_map = {'I-PER':'person' ......}\n \n " ori_label_map = {key: (idx + 1) for (idx, key) in enumerate(label_map.keys())} ori_label_map['O'] = 0 features = [] for (ex_index, example) in...
def get_data_loader(train_examples, label_list, max_seq_length, tokenizer, batch_size, sampler): train_features = convert_examples_to_features(train_examples, label_list, max_seq_length, tokenizer) all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long) all_input_mask = torch...
def get_data_loader_lm(train_examples, label_map, max_seq_length, tokenizer, batch_size, sampler, subword_map): train_features = convert_examples_to_features_lm(train_examples, label_map, max_seq_length, tokenizer, subword_map) all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.lo...
def show_topk_frac(label_token_map, k=2, filter_ratio=0.8, lm_entity_freq=None): (entity_freq, data_label_token_map) = count_entity_freq(args.raw_data_file) label_map = {} for (label_name, token_frac_dict) in label_token_map.items(): cnt = 0 if (args.sort_method == 'timesup'): ...
def filter_is_overlap(token, label_name, label_filter, entity_label_map): if ((len(token) > 3) and (token not in label_filter) and ('##' not in token)): for (key, value) in entity_label_map.items(): if (key == label_name): continue if (token in value): ...
def collect_entity_token(data_path): label_map = {} with open(data_path, 'r') as f: data = f.readlines() for row in data: item = row.strip() if ((item != '') and (item != '-DOCSTART- -X- -X- O')): splits = item.split() token = splits[0] ...
def count_entity_freq(data_path): entity_freq = collections.defaultdict(dict) label_map = collections.defaultdict(dict) with open(data_path, 'r') as f: lines = f.readlines() for line in lines: if ((len(line) < 2) or ('-DOCSTART-' in line)): continue line = line.stri...
def count_entity_freq_roberta(data_path): entity_freq = collections.defaultdict(dict) label_map = collections.defaultdict(dict) with open(data_path, 'r') as f: lines = f.readlines() first = True for line in lines: if ((len(line) < 2) or ('-DOCSTART-' in line)): first = ...
def get_lm_entity_freq(label_frac): entity_freq = collections.defaultdict(dict) for (label, token_frac_dict) in label_frac.items(): for (token, freq) in token_frac_dict.items(): entity_freq[token][label] = freq return entity_freq
def get_label_from_label_token(token_list, label_map, mode='IO'): "\n label_map = {'person':'PER',\n 'location': 'LOC'\n ...\n ...\n }\n " label_list = [] past_label = '' for i in range(len(token_list)): tok...
def filter_item(item_list, subword_mask, input_mask): clean_item_list = [] for (item, not_subword, not_mask) in zip(item_list, subword_mask, input_mask): if (not_subword == 0): continue if (not_mask == 0): break clean_item_list.append(item) return clean_item...
def get_label_token_from_topk(pred_ids_topk, tokenizer, label_map, seq_len=None): if (seq_len == None): seq_len = pred_ids_topk.shape[0] label_list = label_map.values() pred_token = [] for i in range(seq_len): top_k_token = tokenizer.convert_ids_to_tokens(pred_ids_topk[i][:]) f...
def get_label_from_ids(ori_label_ids, subword, input_mask, label_map): ori_label_map = {key: (idx + 1) for (idx, key) in enumerate(label_map.keys())} ids_label_map = {value: key for (key, value) in ori_label_map.items()} ids_label_map[0] = 'O' batch_size = ori_label_ids.shape[0] label_list = [] ...
def get_label_from_logits(logits, label_ids, input_ids, subword, input_mask, tokenizer, label_map, k=1, mode='IO', print_topk=0): pred_ids_topk = torch.topk(logits, k=k, dim=2).indices if (print_topk > 0): (pred_value_top5, pred_ids_top5) = torch.topk(logits, k=print_topk, dim=2) pred_labels = [] ...
def parse_args(): parser = argparse.ArgumentParser(description='Finetune a transformers model on a text classification task (NER) with accelerate library') parser.add_argument('--dataset_name', type=str, default=None, help='The name of the dataset to use (via the datasets library).') parser.add_argument('...
def main(): args = parse_args() accelerator = Accelerator() logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) logger.info(accelerator.state) logger.setLevel((logging.INFO if accelerator.is_local_main_process else log...
class DataCollatorForLMTokanClassification(DataCollatorForTokenClassification): def __call__(self, features): label_name = ('label' if ('label' in features[0].keys()) else 'labels') labels = ([feature[label_name] for feature in features] if (label_name in features[0].keys()) else None) or...
def sample_data(data_path, output_path, k=10): with open(data_path, 'r') as f: few_shot_data = [] label_cnt_dict = {} data = f.readlines() random.shuffle(data) for row in data: item = eval(row) label = item['label'] if (len(label) <= 10):...