code
stringlengths
17
6.64M
def main(): parser = argparse.ArgumentParser() parser.add_argument('--mode', default='glove') parser.add_argument('--name') args = parser.parse_args() args = parser.parse_args() train = spider.SpiderDataset(paths=('data/spider-20190205/train_spider.json', 'data/spider-20190205/train_others.jso...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', required=True) parser.add_argument('--config-args') args = parser.parse_args() if args.config_args: config = json.loads(_jsonnet.evaluate_file(args.config, tla_codes={'args': args.config_args})) else: ...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', required=True) parser.add_argument('--config-args') parser.add_argument('--output', required=True) args = parser.parse_args() if args.config_args: config = json.loads(_jsonnet.evaluate_file(args.config, tla_...
class IdentitySet(collections.abc.MutableSet): def __init__(self, iterable=()): self.map = {id(x): x for x in iterable} def __contains__(self, value): return (id(value) in self.map) def __iter__(self): return self.map.values() def __len__(self): return len(self.map)...
@attr.s class TypeInfo(): name = attr.ib() base_name = attr.ib() predecessor_name = attr.ib() predecessor_triple = attr.ib() unset_fields = attr.ib() preset_fields = attr.ib() preset_seq_elem_counts = attr.ib(factory=(lambda : collections.Counter()))
@attr.s(frozen=True) class Primitive(): value = attr.ib()
class TreeBPE(): def __init__(self, grammar): self.grammar = grammar self.ast_wrapper = grammar.ast_wrapper self.type_infos = {k: TypeInfo(name=k, base_name=k, predecessor_name=k, predecessor_triple=None, unset_fields=collections.OrderedDict(((field.name, field) for field in v.fields)), p...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', required=True) parser.add_argument('--config-args') parser.add_argument('--section', default='train') parser.add_argument('--num-iters', type=int, default=100) parser.add_argument('--vis-out') args = parser.pars...
class ASTWrapperVisitor(asdl.VisitorBase): 'Used by ASTWrapper to collect information.\n\n - put constructors in one place.\n - checks that all fields have names.\n - get all optional fields.\n ' def __init__(self): super(ASTWrapperVisitor, self).__init__() self.constructors = {} ...
class FilterType(): def __init__(self, typ): self.typ = typ def __call__(self, x): return isinstance(x, self.typ)
def is_singleton(x): return ((x is True) or (x is False) or (x is None))
class ASTWrapper(object): 'Provides helper methods on the ASDL AST.' default_primitive_type_checkers = {'identifier': FilterType(str), 'int': FilterType(int), 'string': FilterType(str), 'bytes': FilterType(bytes), 'object': FilterType(object), 'singleton': is_singleton} def __init__(self, ast_def, custom...
@attr.s class HoleValuePlaceholder(): id = attr.ib() field_name = attr.ib() type = attr.ib() is_seq = attr.ib() is_opt = attr.ib()
@attr.s class Hypothesis(): inference_state = attr.ib() next_choices = attr.ib() score = attr.ib(default=0) choice_history = attr.ib(factory=list) score_history = attr.ib(factory=list)
def beam_search(model, orig_item, preproc_item, beam_size, max_steps, visualize_flag=False): (inference_state, next_choices) = model.begin_inference(orig_item, preproc_item) beam = [Hypothesis(inference_state, next_choices)] finished = [] for step in range(max_steps): if visualize_flag: ...
class Barrier(object): def __init__(self, parties, action=(lambda : None)): self._parties = parties self._action = action self._cond = asyncio.Condition() self._count = 0 async def wait(self): self._count += 1 with (await self._cond): if self._mayb...
@attr.s class ResultHandle(object): coro = attr.ib() node = attr.ib() all_results = attr.ib() accessor = attr.ib(default=(lambda x: x)) def __await__(self): result = self.all_results.get(self.node) if (result is None): (yield from self.coro().__await__()) r...
@attr.s(frozen=True, cmp=False, hash=False) class BatchKey(object): callable = attr.ib() args = attr.ib() kwargs = attr.ib() def __attrs_post_init__(self): if isinstance(self.callable, functools.partial): callable_exp = (self.callable.func, self.callable.args, tuple(((k, v) for (k...
@attr.s(cmp=False) class Node(object): args = attr.ib() kwargs = attr.ib() batch_key = attr.ib() depth = attr.ib(default=0) outgoing = attr.ib(default=attr.Factory(list)) num_incoming = attr.ib(default=0)
class StreamingMean(object): def __init__(self): self.value = None self.count = 0.0 def add(self, value): if (not self.count): self.value = value else: self.value *= (self.count / (self.count + 1)) self.value += (value / (self.count + 1)) ...
class TorchBatcher(object): def __init__(self): self.barrier = None self._reset() def _reset(self): self.enqueued_nodes = [] self.results = {} self.mean_depth_by_key = collections.defaultdict(StreamingMean) def __call__(self, callable, *args, **kwargs): b...
class TorchNoOpBatcher(TorchBatcher): async def __call__(self, callable, *args, **kwargs): args = [self._noop_stack(arg) for arg in args] kwargs = {k: self._noop_stack(arg) for (k, arg) in kwargs.items()} return self._noop_unstack(callable(*args, **kwargs)) def _noop_stack(self, item...
def test_streaming_mean(): m = batcher.StreamingMean() values = list(range(10, 20)) for (i, value) in enumerate(values): m.add(value) assert (m.value == np.mean(values[:(i + 1)]))
def test_simple_linear(): batch_size = 32 linear = unittest.mock.Mock(wraps=torch.nn.Linear(8, 16)) inp = torch.autograd.Variable(torch.rand(batch_size, 8)) batcher = torch_batcher.TorchBatcher() async def process(item): result = (await batcher(linear, item)) return result res...
def test_simple_linear_defer(): batch_size = 4 linear = unittest.mock.Mock(wraps=torch.nn.Linear(8, 16)) inp = torch.autograd.Variable(torch.rand(batch_size, 8)) batcher = torch_batcher.TorchBatcher() async def process(item1, item2): result1 = batcher(linear, item1) result2 = batc...
def test_multi_stage(): batch_size = 32 linear = unittest.mock.Mock(wraps=torch.nn.Linear(8, 8)) inp = torch.autograd.Variable(torch.rand(batch_size, 8)) batcher = torch_batcher.TorchBatcher() async def process(item, iters): for iter in range(iters): item = (await batcher(line...
def test_multi_stage_deferred(): batch_size = 32 linear = unittest.mock.Mock(wraps=torch.nn.Linear(8, 8)) inp = torch.autograd.Variable(torch.rand(batch_size, 8)) batcher = torch_batcher.TorchBatcher() async def process(item, iters): for iter in range(iters): item = batcher(li...
def test_multi_stage_and_modules(): batch_size = 32 linears = [unittest.mock.Mock(wraps=torch.nn.Linear(8, 8)) for _ in range(5)] inp = torch.autograd.Variable(torch.rand(batch_size, 8)) batcher = torch_batcher.TorchBatcher() async def process(i, item, iters): for iter in range(iters): ...
def test_multi_args(): batch_size = 32 add = unittest.mock.Mock(wraps=torch.nn.Bilinear(1, 1, 1)) inp = torch.autograd.Variable(torch.arange(batch_size).view((- 1), 1)) batcher = torch_batcher.TorchBatcher() async def process(item, iters): for iter in range(iters): item = (awa...
def test_multi_args_deferred(): batch_size = 32 add = unittest.mock.Mock(wraps=torch.nn.Bilinear(1, 1, 1)) inp = torch.autograd.Variable(torch.arange(batch_size).view((- 1), 1)) batcher = torch_batcher.TorchBatcher() async def process(item, iters): for iter in range(iters): it...
def test_multi_args_mixed_deferred(): batch_size = 6 add = unittest.mock.Mock(wraps=torch.nn.Bilinear(1, 1, 1)) inp = torch.autograd.Variable(torch.arange(batch_size).view((- 1), 1)) double = (lambda x: (x * 2)) sum = (lambda *args: torch.sum(torch.cat(args, dim=1), dim=1)) batcher = torch_bat...
def test_multi_shape(): sizes = [((i // 4) + 1) for i in range(32)] random.seed(32) random.shuffle(sizes) inps = [] for size in sizes: inps.append(torch.rand(size)) with unittest.mock.patch('torch.exp', wraps=torch.exp) as mock: batcher = torch_batcher.TorchBatcher() a...
def test_partial_softmax(): import functools batch_size = 32 inp = torch.autograd.Variable(torch.rand(batch_size, 8)) torch_softmax = functools.partial(unittest.mock.Mock(wraps=torch.nn.functional.softmax), dim=(- 1)) batcher = torch_batcher.TorchBatcher() async def process(item): ret...
def test_partial_max(): import functools batch_size = 3 inp = torch.autograd.Variable(torch.rand(batch_size, 8)) torch_max = functools.partial(unittest.mock.Mock(wraps=torch.max), dim=(- 1)) torch_get = (lambda x, i: x[(range(x.shape[0]), i.view((- 1)))]) double = (lambda x: (x * 2)) batch...
@attr.s class DjangoItem(): text = attr.ib() code = attr.ib() str_map = attr.ib()
@registry.register('dataset', 'django') class DjangoDataset(torch.utils.data.Dataset): def __init__(self, path, limit=None): self.path = path self.examples = [] for line in itertools.islice(open(self.path), limit): example = json.loads(line) self.examples.append(Dj...
@attr.s class HearthstoneItem(): text = attr.ib() code = attr.ib()
@registry.register('dataset', 'hearthstone') class HearthstoneDataset(torch.utils.data.Dataset): def __init__(self, path, limit=None): self.path = path self.examples = [] for example in itertools.islice(zip(open((self.path + '.in')), open((self.path + '.out'))), limit): proces...
def tokenize_for_bleu_eval(code): code = re.sub('([^A-Za-z0-9_])', ' \\1 ', code) code = re.sub('([a-z])([A-Z])', '\\1 \\2', code) code = re.sub('\\s+', ' ', code) code = code.replace('"', '`') code = code.replace("'", '`') tokens = [t for t in code.split(' ') if t] return tokens
@attr.s class IdiomAstItem(): text = attr.ib() code = attr.ib() orig = attr.ib() str_map = attr.ib()
@registry.register('dataset', 'idiom_ast') class IdiomAstDataset(torch.utils.data.Dataset): def __init__(self, path, limit=None): self.path = path self.examples = [] for line in itertools.islice(open(self.path), limit): example = json.loads(line) if isinstance(exam...
@attr.s class SpiderItem(): text = attr.ib() code = attr.ib() schema = attr.ib() orig = attr.ib() orig_schema = attr.ib()
@attr.s class Column(): id = attr.ib() table = attr.ib() name = attr.ib() unsplit_name = attr.ib() orig_name = attr.ib() type = attr.ib() foreign_key_for = attr.ib(default=None)
@attr.s class Table(): id = attr.ib() name = attr.ib() unsplit_name = attr.ib() orig_name = attr.ib() columns = attr.ib(factory=list) primary_keys = attr.ib(factory=list)
@attr.s class Schema(): db_id = attr.ib() tables = attr.ib() columns = attr.ib() foreign_key_graph = attr.ib() orig = attr.ib()
def load_tables(paths): schemas = {} eval_foreign_key_maps = {} for path in paths: schema_dicts = json.load(open(path)) for schema_dict in schema_dicts: tables = tuple((Table(id=i, name=name.split(), unsplit_name=name, orig_name=orig_name) for (i, (name, orig_name)) in enumerat...
@registry.register('dataset', 'spider') class SpiderDataset(torch.utils.data.Dataset): def __init__(self, paths, tables_paths, db_path, limit=None): self.paths = paths self.db_path = db_path self.examples = [] (self.schemas, self.eval_foreign_key_maps) = load_tables(tables_paths) ...
@registry.register('dataset', 'spider_idiom_ast') class SpiderIdiomAstDataset(torch.utils.data.Dataset): def __init__(self, paths, tables_paths, db_path, limit=None): self.paths = paths self.db_path = db_path self.examples = [] (self.schemas, self.eval_foreign_key_maps) = load_tab...
class HoleType(enum.Enum): ReplaceSelf = 1 AddChild = 2
class MissingValue(): pass
@attr.s class SeqField(): type_name = attr.ib() field = attr.ib()
@registry.register('grammar', 'idiom_ast') class IdiomAstGrammar(): def __init__(self, base_grammar, template_file, root_type=None, all_sections_rewritten=False): self.base_grammar = registry.construct('grammar', base_grammar) self.templates = json.load(open(template_file)) self.all_secti...
def split_string_whitespace_and_camelcase(s): split_space = s.split(' ') result = [] for token in split_space: if token: camelcase_split_token = re.sub('([a-z])([A-Z])', '\\1\ue012\\2', token).split('\ue012') result.extend(camelcase_split_token) result.append(' ') ...
@registry.register('grammar', 'python') class PythonGrammar(): ast_wrapper = ast_util.ASTWrapper(asdl.parse(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Python.asdl'))) root_type = 'Module' pointers = set() @classmethod def parse(cls, code, section): try: py_ast =...
def bimap(first, second): return ({f: s for (f, s) in zip(first, second)}, {s: f for (f, s) in zip(first, second)})
def filter_nones(d): return {k: v for (k, v) in d.items() if ((v is not None) and (v != []))}
def join(iterable, delimiter): it = iter(iterable) (yield next(it)) for x in it: (yield delimiter) (yield x)
def intersperse(delimiter, seq): return itertools.islice(itertools.chain.from_iterable(zip(itertools.repeat(delimiter), seq)), 1, None)
@registry.register('grammar', 'spider') class SpiderLanguage(): root_type = 'sql' def __init__(self, output_from=False, use_table_pointer=False, include_literals=True, include_columns=True): custom_primitive_type_checkers = {} self.pointers = set() if use_table_pointer: cu...
@attr.s class SpiderUnparser(): ast_wrapper = attr.ib() schema = attr.ib() UNIT_TYPES_B = {'Minus': '-', 'Plus': '+', 'Times': '*', 'Divide': '/'} COND_TYPES_B = {'Between': 'BETWEEN', 'Eq': '=', 'Gt': '>', 'Lt': '<', 'Ge': '>=', 'Le': '<=', 'Ne': '!=', 'In': 'IN', 'Like': 'LIKE'} @classmethod ...
class AbstractPreproc(metaclass=abc.ABCMeta): "Used for preprocessing data according to the model's liking.\n\n Some tasks normally performed here:\n - Constructing a vocabulary from the training data\n - Transforming the items in some way, such as\n - Parsing the AST\n - \n - Loading an...
def maybe_mask(attn, attn_mask): if (attn_mask is not None): assert all((((a == 1) or (b == 1) or (a == b)) for (a, b) in zip(attn.shape[::(- 1)], attn_mask.shape[::(- 1)]))), 'Attention mask shape {} should be broadcastable with attention shape {}'.format(attn_mask.shape, attn.shape) attn.data.ma...
class Attention(torch.nn.Module): def __init__(self, pointer): super().__init__() self.pointer = pointer self.softmax = torch.nn.Softmax(dim=(- 1)) def forward(self, query, values, attn_mask=None): attn_logits = self.pointer(query, values, attn_mask) attn = self.softm...
@registry.register('pointer', 'sdp') class ScaledDotProductPointer(torch.nn.Module): def __init__(self, query_size, key_size): super().__init__() self.query_proj = torch.nn.Linear(query_size, key_size) self.temp = np.power(key_size, 0.5) def forward(self, query, keys, attn_mask=None)...
@registry.register('attention', 'sdp') class ScaledDotProductAttention(Attention): def __init__(self, query_size, value_size): super().__init__(ScaledDotProductPointer(query_size, value_size))
@registry.register('pointer', 'bahdanau') class BahdanauPointer(torch.nn.Module): def __init__(self, query_size, key_size, proj_size): super().__init__() self.compute_scores = torch.nn.Sequential(torch.nn.Linear((query_size + key_size), proj_size), torch.nn.Tanh(), torch.nn.Linear(proj_size, 1)) ...
@registry.register('attention', 'bahdanau') class BahdanauAttention(Attention): def __init__(self, query_size, value_size, proj_size): super().__init__(BahdanauPointer(query_size, value_size, proj_size))
class MultiHeadedAttention(torch.nn.Module): def __init__(self, h, query_size, value_size, dropout=0.1): super().__init__() assert ((query_size % h) == 0) assert ((value_size % h) == 0) self.d_k = (value_size // h) self.h = h self.linears = torch.nn.ModuleList([tor...
class ZippedDataset(torch.utils.data.Dataset): def __init__(self, *components): assert (len(components) >= 1) lengths = [len(c) for c in components] assert all(((lengths[0] == other) for other in lengths[1:])), "Lengths don't match: {}".format(lengths) self.components = components...
@registry.register('model', 'EncDec') class EncDecModel(torch.nn.Module): class Preproc(abstract_preproc.AbstractPreproc): def __init__(self, encoder, decoder, encoder_preproc, decoder_preproc): super().__init__() self.enc_preproc = registry.lookup('encoder', encoder['name']).Pre...
class IdiomPreproc(abstract_preproc.AbstractPreproc): def __init__(self, grammar, save_path, censor_pointers): self.save_path = save_path self.censor_pointers = censor_pointers self.grammar = registry.construct('grammar', grammar) self.ast_wrapper = self.grammar.ast_wrapper ...
class AstConverter(): def __init__(self, grammar, censor_pointers): self.grammar = grammar self.ast_wrapper = grammar.ast_wrapper self.symbols = {} self.split_constants = False self.preserve_terminal_types = True self.censor_pointers = censor_pointers def conv...
@registry.register('model', 'IdiomMiner') class IdiomMinerModel(): 'A dummy model for housing IdiomPreproc.' Preproc = IdiomPreproc
class RecurrentDropoutLSTMCell(RNNCellBase): def __init__(self, input_size, hidden_size, dropout=0.0): super(RecurrentDropoutLSTMCell, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.dropout = dropout self.W_i = Parameter(torch.Tensor(hidd...
class ParentFeedingLSTMCell(RNNCellBase): def __init__(self, input_size, hidden_size): super(ParentFeedingLSTMCell, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.W_i = Parameter(torch.Tensor(hidden_size, input_size)) self.U_i = Parameter...
class LSTM(nn.Module): def __init__(self, input_size, hidden_size, bidirectional=False, dropout=0.0, cell_factory=RecurrentDropoutLSTMCell): super(LSTM, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.bidirectional = bidirectional self.dro...
@attr.s class NL2CodeEncoderState(): state = attr.ib() memory = attr.ib() words = attr.ib() def find_word_occurrences(self, word): return [i for (i, w) in enumerate(self.words) if (w == word)]
@registry.register('encoder', 'NL2Code') class NL2CodeEncoder(torch.nn.Module): batched = False class Preproc(abstract_preproc.AbstractPreproc): def __init__(self, save_path, min_freq=3, max_count=5000): self.vocab_path = os.path.join(save_path, 'enc_vocab.json') self.data_di...
class TemplateTraversalType(enum.Enum): DEFAULT = 0 CHILDREN_APPLY = 1 LIST_LENGTH_APPLY = 2
@attr.s(frozen=True) class TemplateTraversalState(): node = attr.ib() parent_field_type = attr.ib() type = attr.ib(default=TemplateTraversalType.DEFAULT)
@attr.s(frozen=True) class TemplateActionProvider(): model = attr.ib() queue = attr.ib() buffer = attr.ib(factory=pyrsistent.pdeque) last_returned = attr.ib(default=None) @classmethod def build(cls, model, tree, parent_field_type): return cls(model, pyrsistent.pdeque([TemplateTraversa...
@attr.s class SpiderEncoderState(): state = attr.ib() memory = attr.ib() question_memory = attr.ib() schema_memory = attr.ib() words = attr.ib() pointer_memories = attr.ib() pointer_maps = attr.ib() def find_word_occurrences(self, word): return [i for (i, w) in enumerate(self....
@attr.s class PreprocessedSchema(): column_names = attr.ib(factory=list) table_names = attr.ib(factory=list) table_bounds = attr.ib(factory=list) column_to_table = attr.ib(factory=dict) table_to_columns = attr.ib(factory=dict) foreign_keys = attr.ib(factory=dict) foreign_keys_tables = attr...
class SpiderEncoderV2Preproc(abstract_preproc.AbstractPreproc): def __init__(self, save_path, min_freq=3, max_count=5000, include_table_name_in_column=True, word_emb=None, count_tokens_in_word_emb_for_vocab=False): if (word_emb is None): self.word_emb = None else: self.wor...
@registry.register('encoder', 'spiderv2') class SpiderEncoderV2(torch.nn.Module): batched = True Preproc = SpiderEncoderV2Preproc def __init__(self, device, preproc, word_emb_size=128, recurrent_size=256, dropout=0.0, question_encoder=('emb', 'bilstm'), column_encoder=('emb', 'bilstm'), table_encoder=('e...
def relative_attention_logits(query, key, relation): qk_matmul = torch.matmul(query, key.transpose((- 2), (- 1))) q_t = query.permute(0, 2, 1, 3) r_t = relation.transpose((- 2), (- 1)) q_tr_t_matmul = torch.matmul(q_t, r_t) q_tr_tmatmul_t = q_tr_t_matmul.permute(0, 2, 1, 3) return ((qk_matmul ...
def relative_attention_values(weight, value, relation): wv_matmul = torch.matmul(weight, value) w_t = weight.permute(0, 2, 1, 3) w_tr_matmul = torch.matmul(w_t, relation) w_tr_matmul_t = w_tr_matmul.permute(0, 2, 1, 3) return (wv_matmul + w_tr_matmul_t)
def clones(module_fn, N): return nn.ModuleList([module_fn() for _ in range(N)])
def attention(query, key, value, mask=None, dropout=None): "Compute 'Scaled Dot Product Attention'" d_k = query.size((- 1)) scores = (torch.matmul(query, key.transpose((- 2), (- 1))) / math.sqrt(d_k)) if (mask is not None): scores = scores.masked_fill((mask == 0), (- 1000000000.0)) p_attn ...
class MultiHeadedAttention(nn.Module): def __init__(self, h, d_model, dropout=0.1): 'Take in model size and number of heads.' super(MultiHeadedAttention, self).__init__() assert ((d_model % h) == 0) self.d_k = (d_model // h) self.h = h self.linears = clones((lambda...
def attention_with_relations(query, key, value, relation_k, relation_v, mask=None, dropout=None): "Compute 'Scaled Dot Product Attention'" d_k = query.size((- 1)) scores = relative_attention_logits(query, key, relation_k) if (mask is not None): scores = scores.masked_fill((mask == 0), (- 10000...
class MultiHeadedAttentionWithRelations(nn.Module): def __init__(self, h, d_model, dropout=0.1): 'Take in model size and number of heads.' super(MultiHeadedAttentionWithRelations, self).__init__() assert ((d_model % h) == 0) self.d_k = (d_model // h) self.h = h sel...
class Encoder(nn.Module): 'Core encoder is a stack of N layers' def __init__(self, layer, layer_size, N, tie_layers=False): super(Encoder, self).__init__() if tie_layers: self.layer = layer() self.layers = [self.layer for _ in range(N)] else: self.l...
class SublayerConnection(nn.Module): '\n A residual connection followed by a layer norm.\n Note for code simplicity the norm is first as opposed to last.\n ' def __init__(self, size, dropout): super(SublayerConnection, self).__init__() self.norm = nn.LayerNorm(size) self.drop...
class EncoderLayer(nn.Module): 'Encoder is made up of self-attn and feed forward (defined below)' def __init__(self, size, self_attn, feed_forward, num_relation_kinds, dropout): super(EncoderLayer, self).__init__() self.self_attn = self_attn self.feed_forward = feed_forward se...
class PositionwiseFeedForward(nn.Module): 'Implements FFN equation.' def __init__(self, d_model, d_ff, dropout=0.1): super(PositionwiseFeedForward, self).__init__() self.w_1 = nn.Linear(d_model, d_ff) self.w_2 = nn.Linear(d_ff, d_model) self.dropout = nn.Dropout(dropout) ...
@registry.register('lr_scheduler', 'warmup_polynomial') @attr.s class WarmupPolynomialLRScheduler(): optimizer = attr.ib() num_warmup_steps = attr.ib() start_lr = attr.ib() end_lr = attr.ib() decay_steps = attr.ib() power = attr.ib() def update_lr(self, current_step): if (current_...
@registry.register('lr_scheduler', 'warmup_cosine') @attr.s class WarmupCosineLRScheduler(): optimizer = attr.ib() num_warmup_steps = attr.ib() start_lr = attr.ib() end_lr = attr.ib() decay_steps = attr.ib() def update_lr(self, current_step): if (current_step < self.num_warmup_steps):...
@registry.register('lr_scheduler', 'noop') class NoOpLRScheduler(): def __init__(self, optimizer): pass def update_lr(self, current_step): pass
@registry.register('optimizer', 'adamw') class AdamW(torch.optim.Optimizer): 'Implements Adam algorithm.\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n ...