code stringlengths 17 6.64M |
|---|
class CoreNLP():
def __init__(self):
if (not os.environ.get('CORENLP_HOME')):
os.environ['CORENLP_HOME'] = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../third_party/stanford-corenlp-full-2018-10-05'))
if (not os.path.exists(os.environ['CORENLP_HOME'])):
ra... |
def annotate(text, annotators=None, output_format=None, properties=None):
global _singleton
if (not _singleton):
_singleton = CoreNLP()
return _singleton.annotate(text, annotators, output_format, properties)
|
class Embedder(metaclass=abc.ABCMeta):
@abc.abstractmethod
def tokenize(self, sentence):
'Given a string, return a list of tokens suitable for lookup.'
pass
@abc.abstractmethod
def untokenize(self, tokens):
'Undo tokenize.'
pass
@abc.abstractmethod
def lookup... |
@registry.register('word_emb', 'glove')
class GloVe(Embedder):
def __init__(self, kind):
cache = os.path.join(os.environ.get('CACHE_DIR', os.getcwd()), '.vector_cache')
self.glove = torchtext.vocab.GloVe(name=kind, cache=cache)
self.dim = self.glove.dim
self.vectors = self.glove.v... |
@registry.register('word_emb', 'bpemb')
class BPEmb(Embedder):
def __init__(self, dim, vocab_size, lang='en'):
self.bpemb = bpemb.BPEmb(lang=lang, dim=dim, vs=vocab_size)
self.dim = dim
self.vectors = torch.from_numpy(self.bpemb.vectors)
def tokenize(self, text):
return self.... |
def argsort(items, key=(lambda x: x), reverse=False):
(orig_to_sort, sorted_items) = zip(*sorted(enumerate(items), key=(lambda x: key(x[1])), reverse=reverse))
sort_to_orig = tuple((x[0] for x in sorted(enumerate(orig_to_sort), key=operator.itemgetter(1))))
return (sorted_items, sort_to_orig, orig_to_sort... |
def sort_lists_by_length(lists):
return argsort(lists, key=len, reverse=True)
|
def batch_bounds_for_packing(lengths):
'Returns how many items in batch have length >= i at step i.\n Examples:\n [5] -> [1, 1, 1, 1, 1]\n [5, 5] -> [2, 2, 2, 2, 2]\n [5, 3] -> [2, 2, 2, 1, 1]\n [5, 4, 1, 1] -> [4, 2, 2, 2, 1]\n '
last_length = 0
count = len(lengths)
result =... |
def _make_packed_sequence(data, batch_sizes):
return torch.nn.utils.rnn.PackedSequence(data, torch.LongTensor(batch_sizes).to(data.device))
|
@attr.s(frozen=True)
class PackedSequencePlus():
ps = attr.ib()
lengths = attr.ib()
sort_to_orig = attr.ib(converter=np.array)
orig_to_sort = attr.ib(converter=np.array)
@lengths.validator
def descending(self, attribute, value):
for (x, y) in zip(value, value[1:]):
if (not... |
def compute_metrics(config_path, config_args, section, inferred_path, logdir=None, evaluate_beams_individually=False):
if config_args:
config = json.loads(_jsonnet.evaluate_file(config_path, tla_codes={'args': config_args}))
else:
config = json.loads(_jsonnet.evaluate_file(config_path))
if... |
def load_from_lines(inferred_lines):
for line in inferred_lines:
infer_results = json.loads(line)
if infer_results.get('beams', ()):
inferred_code = infer_results['beams'][0]['inferred_code']
else:
inferred_code = None
(yield (inferred_code, infer_results))
|
def evaluate_default(data, inferred_lines):
metrics = data.Metrics(data)
for (inferred_code, infer_results) in load_from_lines(inferred_lines):
if ('index' in infer_results):
metrics.add(data[infer_results['index']], inferred_code)
else:
metrics.add(None, inferred_code,... |
def evaluate_all_beams(data, inferred_lines):
metrics = data.Metrics(data)
results = []
for (_, infer_results) in load_from_lines(inferred_lines):
for_beam = metrics.evaluate_all(infer_results['index'], data[infer_results['index']], [beam['inferred_code'] for beam in infer_results.get('beams', ())... |
def read_index(filename):
index = []
with open(filename) as index_file:
while True:
offset = index_file.read(8)
if (not offset):
break
(offset,) = struct.unpack('<Q', offset)
index.append(offset)
return index
|
class IndexedFileWriter(object):
def __init__(self, path):
self.f = open(path, 'wb')
self.index_f = open((path + '.index'), 'wb')
def append(self, record):
offset = self.f.tell()
self.f.write(record)
self.index_f.write(struct.pack('<Q', offset))
def close(self):
... |
class IndexedFileReader(object):
def __init__(self, path):
self.f = open(path, 'rb')
self.index = read_index((path + '.index'))
self.lengths = [(end - start) for (start, end) in zip(([0] + self.index), (self.index + [os.path.getsize(path)]))]
def __len__(self):
return len(sel... |
class Parallelizer(ABC):
'\n A parallelizer is a general purpose task used to handle the situation of\n executing functions f(x) on a series of functions and inputs f_i, x_i, where\n f is often quite large and thus difficult to transport to a given\n process, but there are typically fewer ... |
class CPUParallelizer(Parallelizer):
def start_worker(self, f, input_queue, output_queue):
worker = multiprocessing.Process(target=self.multi_processing_worker, args=(f, input_queue, output_queue))
worker.start()
def create_queue(self):
return multiprocessing.Queue()
@staticmeth... |
class RandomState():
def __init__(self):
self.random_mod_state = random.getstate()
self.np_state = np.random.get_state()
self.torch_cpu_state = torch.get_rng_state()
self.torch_gpu_states = [torch.cuda.get_rng_state(d) for d in range(torch.cuda.device_count())]
def restore(se... |
class RandomContext():
'Save and restore state of PyTorch, NumPy, Python RNGs.'
def __init__(self, seed=None):
outside_state = RandomState()
random.seed(seed)
np.random.seed(seed)
if (seed is None):
torch.manual_seed(random.randint(((- sys.maxsize) - 1), sys.maxsiz... |
def register(kind, name):
kind_registry = _REGISTRY[kind]
def decorator(obj):
if (name in kind_registry):
raise LookupError('{} already registered as kind {}'.format(name, kind))
kind_registry[name] = obj
return obj
return decorator
|
def lookup(kind, name):
if isinstance(name, collections.abc.Mapping):
name = name['name']
if (kind not in _REGISTRY):
raise KeyError('Nothing registered under "{}"'.format(kind))
return _REGISTRY[kind][name]
|
def construct(kind, config, unused_keys=(), **kwargs):
return instantiate(lookup(kind, config), config, (unused_keys + ('name',)), **kwargs)
|
def instantiate(callable, config, unused_keys=(), **kwargs):
merged = {**config, **kwargs}
signature = inspect.signature(callable)
for (name, param) in signature.parameters.items():
if (param.kind in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.VAR_POSITIONAL)):
raise ValueErr... |
class ArgsDict(dict):
def __init__(self, **kwargs):
super(ArgsDict, self).__init__()
for (key, value) in kwargs.items():
self[key] = value
self.__dict__ = self
|
def load_checkpoint(model, optimizer, model_dir, map_location=None, step=None):
path = os.path.join(model_dir, 'model_checkpoint')
if (step is not None):
path += '-{:08d}'.format(step)
if os.path.exists(path):
print(('Loading model from %s' % path))
checkpoint = torch.load(path, ma... |
def load_and_map_checkpoint(model, model_dir, remap):
path = os.path.join(model_dir, 'model_checkpoint')
print(('Loading parameters %s from %s' % (remap.keys(), model_dir)))
checkpoint = torch.load(path)
new_state_dict = model.state_dict()
for (name, value) in remap.items():
new_state_dict... |
def save_checkpoint(model, optimizer, step, model_dir, ignore=[], keep_every_n=10000000):
if (not os.path.exists(model_dir)):
os.makedirs(model_dir)
path_without_step = os.path.join(model_dir, 'model_checkpoint')
step_padded = format(step, '08d')
state_dict = model.state_dict()
if ignore:
... |
class Saver(object):
'Class to manage save and restore for the model and optimizer.'
def __init__(self, model, optimizer, keep_every_n=None):
self._model = model
self._optimizer = optimizer
self._keep_every_n = keep_every_n
def restore(self, model_dir, map_location=None, step=Non... |
def to_dict_with_sorted_values(d, key=None):
return {k: sorted(v, key=key) for (k, v) in d.items()}
|
def to_dict_with_set_values(d):
result = {}
for (k, v) in d.items():
hashable_v = []
for v_elem in v:
if isinstance(v_elem, list):
hashable_v.append(tuple(v_elem))
else:
hashable_v.append(v_elem)
result[k] = set(hashable_v)
re... |
def tuplify(x):
if (not isinstance(x, (tuple, list))):
return x
return tuple((tuplify(elem) for elem in x))
|
def test_argsort_properties():
for items in (tuple(range(10)), (9, 8, 7, 6, 5, 4, 3, 2, 1, 0), (0, 2, 4, 6, 8, 1, 3, 5, 7, 9), (0, 9, 1, 8, 2, 7, 3, 6, 4, 5)):
(sorted_items, sort_to_orig, orig_to_sort) = batched_sequence.argsort(items)
for i in range(len(items)):
assert (items[orig_to... |
def func_1(x, y):
time.sleep((random.random() * 0.1))
return ((x * 10) + y)
|
def func_2(x, y):
return x(y)
|
def test_parallelizer():
p = parallelizer.CPUParallelizer(4)
results = list(p.parallel_map(func_1, [(2, [3, 4, 5]), (3, [4, 5, 6]), (4, [])]))
assert (results == [23, 24, 25, 34, 35, 36]), str(results)
p = parallelizer.CPUParallelizer(1)
from_parent = 1
results = list(p.parallel_map(func_2, [(... |
class Sentinel(object):
'Used to represent special values like UNK.'
__slots__ = ('name',)
def __init__(self, name):
self.name = name
def __repr__(self):
return (('<' + self.name) + '>')
def __lt__(self, other):
if isinstance(other, IndexedSet.Sentinel):
retu... |
class Vocab(collections.abc.Set):
def __init__(self, iterable, special_elems=(UNK, BOS, EOS)):
elements = list(special_elems)
elements.extend(iterable)
assert (len(elements) == len(set(elements)))
self.id_to_elem = {i: elem for (i, elem) in enumerate(elements)}
self.elem_t... |
class VocabBuilder():
def __init__(self, min_freq=None, max_count=None):
self.word_freq = collections.Counter()
self.min_freq = min_freq
self.max_count = max_count
def add_word(self, word, count=1):
self.word_freq[word] += count
def finish(self, *args, **kwargs):
... |
def clean_sql_file(input_sql_file, output_sql_file):
print(input_sql_file)
f = open(input_sql_file)
f_out = open(output_sql_file, 'w')
cnt = 0
for line in f.readlines():
(sql, db) = line.split('\t')
if (not sql.endswith(';')):
sql = (sql + ';')
f_out.write((sql ... |
class Grammar(object):
def __init__(self, rules):
'\n instantiate a grammar with a set of production rules of type Rule\n '
self.rules = rules
self.rule_index = defaultdict(list)
self.rule_to_id = OrderedDict()
node_types = set()
lhs_nodes = set()
... |
class IFTTTGrammar(Grammar):
def __init__(self, rules):
super(IFTTTGrammar, self).__init__(rules)
def is_value_node(self, node):
return False
|
def is_builtin_type(x):
return ((x == str) or (x == int) or (x == float) or (x == bool) or (x == object) or (x == 'identifier'))
|
def is_terminal_ast_type(x):
if (inspect.isclass(x) and (x in TERMINAL_AST_TYPES)):
return True
return False
|
def type_str_to_type(type_str):
if (type_str.endswith('*') or (type_str == 'root') or (type_str == 'epsilon')):
return type_str
else:
try:
type_obj = eval(type_str)
if is_builtin_type(type_obj):
return type_obj
except:
pass
tr... |
def is_compositional_leaf(node):
is_leaf = True
for (field_name, field_value) in ast.iter_fields(node):
if (field_name in NODE_FIELD_BLACK_LIST):
continue
if (field_value is None):
is_leaf &= True
elif (isinstance(field_value, list) and (len(field_value) == 0)):... |
class PythonGrammar(Grammar):
def __init__(self, rules):
super(PythonGrammar, self).__init__(rules)
def is_value_node(self, node):
return is_builtin_type(node.type)
|
def is_builtin_type(x):
return ((x == str) or (x == int) or (x == float) or (x == bool) or (x == object) or (x == 'identifier'))
|
def type_str_to_type(type_str):
return type_str
|
def is_compositional_leaf(node):
is_leaf = True
for (field_name, field_value) in ast.iter_fields(node):
if (field_name in NODE_FIELD_BLACK_LIST):
continue
if (field_value is None):
is_leaf &= True
elif (isinstance(field_value, list) and (len(field_value) == 0)):... |
class SQLGrammar(Grammar):
def __init__(self, rules):
super(SQLGrammar, self).__init__(rules)
def is_value_node(self, node):
return (node.type in TERMINAL_AST_TYPES)
|
def indexesFromSentence(lang, sentence):
return [lang.word2index[word] for word in sentence.split(' ')]
|
def variableFromSentence(lang, sentence):
indexes = indexesFromSentence(lang, sentence)
indexes.append(EOS_token)
result = Variable(torch.LongTensor(indexes).view((- 1), 1))
if use_cuda:
return result.cuda()
else:
return result
|
def variablesFromPair(pair):
input_variable = variableFromSentence(input_lang, pair[0])
target_variable = variableFromSentence(output_lang, pair[1])
return (input_variable, target_variable)
|
def train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_LENGTH, use_attention=True):
encoder_hidden = encoder.initHidden()
encoder_optimizer.zero_grad()
decoder_optimizer.zero_grad()
input_length = input_variable.size()[0]
target... |
def asMinutes(s):
m = math.floor((s / 60))
s -= (m * 60)
return ('%dm %ds' % (m, s))
|
def timeSince(since, percent):
now = time.time()
s = (now - since)
es = (s / percent)
rs = (es - s)
return ('%s (- %s)' % (asMinutes(s), asMinutes(rs)))
|
def trainIters(encoder, decoder, n_iters, print_every=1000, plot_every=100, learning_rate=0.01, use_attention=True):
start = time.time()
plot_losses = []
print_loss_total = 0
plot_loss_total = 0
encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate)
decoder_optimizer = optim.SGD... |
def showPlot(points):
plt.figure()
(fig, ax) = plt.subplots()
loc = ticker.MultipleLocator(base=0.2)
ax.yaxis.set_major_locator(loc)
plt.plot(points)
|
def evaluate(encoder, decoder, sentence, max_length=MAX_LENGTH, use_attention=True):
input_variable = variableFromSentence(input_lang, sentence)
input_length = input_variable.size()[0]
encoder_hidden = encoder.initHidden()
encoder_outputs = Variable(torch.zeros(max_length, encoder.hidden_size))
en... |
def evaluateRandomly(encoder, decoder, use_attention=True, n=10):
for i in range(n):
pair = random.choice(train_pairs)
print('>', pair[0])
print('=', pair[1])
(output_words, attentions) = evaluate(encoder, decoder, pair[0], use_attention=use_attention)
output_sentence = ' '... |
def evaluateAll(encoder, decoder, split='dev', use_attention=True):
if use_attention:
model = 'attention'
else:
model = 'simple'
if (split == 'train'):
eval_pairs = train_pairs
elif (split == 'dev'):
eval_pairs = dev_pairs
translated_sentences = []
target_senten... |
def extract_grammar(code_file, prefix='py'):
line_num = 0
parse_trees = []
for line in open(code_file):
code = line.strip()
parse_tree = parse(code)
parse_trees.append(parse_tree)
ast_tree = parse_tree_to_python_ast(parse_tree)
ref_ast_tree = ast.parse(canonicalize_... |
def rule_vs_node_stat():
line_num = 0
parse_trees = []
code_file = '/Users/yinpengcheng/Research/SemanticParsing/CodeGeneration/card_datasets/hearthstone/all_hs.out'
node_nums = rule_nums = 0.0
for line in open(code_file):
code = line.replace('§', '\n').strip()
parse_tree = parse(c... |
def process_heart_stone_dataset():
data_file = '/Users/yinpengcheng/Research/SemanticParsing/CodeGeneration/card_datasets/hearthstone/all_hs.out'
parse_trees = []
rule_num = 0.0
example_num = 0
for line in open(data_file):
code = line.replace('§', '\n').strip()
parse_tree = parse(c... |
def canonicalize_sql_example(query, sql, ast):
query = re.sub('<.*?>', '', query)
query_tokens = nltk.word_tokenize(query)
parse_tree = parse_raw(ast)
return (query_tokens, sql, parse_tree)
|
def preprocess_sql_dataset(data_file, ast_file):
f = open('sql_dataset.examples.txt', 'w')
ast_data = json.load(open(ast_file, 'r'))
data = json.load(open(data_file))
ast_data = ast_data['statement']
examples = []
for (idx, (item, ast)) in enumerate(zip(data, ast_data)):
nl = item['que... |
def get_terminal_tokens(_terminal_str):
'\n get terminal tokens\n break words like MinionCards into [Minion, Cards]\n '
tmp_terminal_tokens = [t for t in _terminal_str.split(' ') if (len(t) > 0)]
_terminal_tokens = []
for token in tmp_terminal_tokens:
sub_tokens = re.sub('([a-z])([A-Z... |
def load_table_schema_data(inputfile):
data = json.load(open(inputfile))
terminal_tokens = []
db_dict = dict()
for db in data:
db_dict[db['db_id']] = db
for col in db['column_names_original']:
terminal_tokens.append(col[1])
for table in db['table_names_original']:
... |
def gen_db_mask(vocab, non_schema_vocab_size, db_file):
db_dict = dict()
vocab_size = vocab.size
data = json.load(open(db_file))
for db in data:
mask = np.zeros(vocab_size, dtype='int32')
mask[:non_schema_vocab_size] = 1
for col in db['column_names_original']:
idx =... |
def parse_train_dataset(args):
MAX_QUERY_LENGTH = 70
WORD_FREQ_CUT_OFF = 0
train_data = preprocess_sql_dataset(args.train_data, args.train_data_ast)
dev_data = preprocess_sql_dataset(args.dev_data, args.dev_data_ast)
test_data = preprocess_sql_dataset(args.test_data, args.test_data_ast)
data =... |
def dump_data_for_evaluation(data_type='django', data_file='', max_query_length=70):
(train_data, dev_data, test_data) = deserialize_from_file(data_file)
prefix = '/Users/yinpengcheng/Projects/dl4mt-tutorial/codegen_data/'
for (dataset, output) in [(train_data, (prefix + ('%s.train' % data_type))), (dev_d... |
def typename(x):
if isinstance(x, basestring):
return x
return x.__name__
|
def escape(text):
text = text.replace('"', '-``-').replace("'", '-`-').replace(' ', '-SP-').replace('\t', '-TAB-').replace('\n', '-NL-').replace('\r', '-NL2-').replace('(', '-LRB-').replace(')', '-RRB-').replace('|', '-BAR-')
if (text is None):
return '-NONE-'
elif (text == ''):
return '-E... |
def unescape(text):
if (text == '-NONE-'):
return None
text = text.replace('-``-', '"').replace('-`-', "'").replace('-SP-', ' ').replace('-TAB-', '\t').replace('-NL-', '\n').replace('-NL2-', '\r').replace('-LRB-', '(').replace('-RRB-', ')').replace('-BAR-', '|').replace('-EMPTY-', '')
return text
|
def softmax(x):
return T.nnet.softmax(x.reshape(((- 1), x.shape[(- 1)]))).reshape(x.shape)
|
def time_distributed_softmax(x):
import warnings
warnings.warn('time_distributed_softmax is deprecated. Just use softmax!', DeprecationWarning)
return softmax(x)
|
def softplus(x):
return T.nnet.softplus(x)
|
def relu(x):
return T.nnet.relu(x)
|
def tanh(x):
return T.tanh(x)
|
def sigmoid(x):
return T.nnet.sigmoid(x)
|
def hard_sigmoid(x):
return T.nnet.hard_sigmoid(x)
|
def linear(x):
'\n The function returns the variable that is passed in, so all types work\n '
return x
|
def get(identifier):
return get_from_module(identifier, globals(), 'activation function')
|
class Convolution2d(Layer):
'a convolutional layer with max pooling'
def __init__(self, max_sent_len, word_embed_dim, filter_num, filter_window_size, border_mode='valid', activation='relu', name='Convolution2d'):
super(Convolution2d, self).__init__()
self.init = initializations.get('uniform')... |
class Layer(object):
def __init__(self):
self.params = []
def init_updates(self):
self.updates = []
def __call__(self, X):
return X
def supports_masked_input(self):
' Whether or not this layer respects the output mask of its previous layer in its calculations. If yo... |
class MaskedLayer(Layer):
'\n If your layer trivially supports masking (by simply copying the input mask to the output), then subclass MaskedLayer\n instead of Layer, and make sure that you incorporate the input mask into your calculation of get_output()\n '
def supports_masked_input(self):
... |
class Dense(Layer):
def __init__(self, input_dim, output_dim, init='glorot_uniform', activation='tanh', name='Dense'):
super(Dense, self).__init__()
self.init = initializations.get(init)
self.activation = activations.get(activation)
self.input_dim = input_dim
self.output_d... |
class Dropout(Layer):
def __init__(self, p, srng, name='dropout'):
super(Dropout, self).__init__()
assert (0.0 < p < 1.0)
self.p = p
self.srng = srng
if (name is not None):
self.set_name(name)
def __call__(self, X, train_only=True):
retain_prob = (... |
class WordDropout(Layer):
def __init__(self, p, srng, name='WordDropout'):
super(WordDropout, self).__init__()
self.p = p
self.srng = srng
def __call__(self, X, train_only=True):
retain_prob = (1.0 - self.p)
mask = self.srng.binomial(X.shape[:(- 1)], p=retain_prob, dt... |
def get_embed_iter(file_path):
for line in open(file_path):
line = line.strip()
data = line.split(' ')
word = data[0]
embed = np.asarray([float(e) for e in data[1:]], dtype='float32')
(yield (word, embed))
|
class Embedding(Layer):
'\n Turn positive integers (indexes) into denses vectors of fixed size.\n eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]\n\n @input_dim: size of vocabulary (highest input integer + 1)\n @out_dim: size of dense representation\n '
def __init__(self, input_d... |
class HybridEmbedding(Layer):
'\n Turn positive integers (indexes) into denses vectors of fixed size.\n eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]\n\n @input_dim: size of vocabulary (highest input integer + 1)\n @out_dim: size of dense representation\n '
def __init__(self, e... |
def mean_squared_error(y_true, y_pred):
return T.sqr((y_pred - y_true)).mean(axis=(- 1))
|
def mean_absolute_error(y_true, y_pred):
return T.abs_((y_pred - y_true)).mean(axis=(- 1))
|
def mean_absolute_percentage_error(y_true, y_pred):
return (T.abs_(((y_true - y_pred) / T.clip(T.abs_(y_true), epsilon, np.inf))).mean(axis=(- 1)) * 100.0)
|
def mean_squared_logarithmic_error(y_true, y_pred):
return T.sqr((T.log((T.clip(y_pred, epsilon, np.inf) + 1.0)) - T.log((T.clip(y_true, epsilon, np.inf) + 1.0)))).mean(axis=(- 1))
|
def squared_hinge(y_true, y_pred):
return T.sqr(T.maximum((1.0 - (y_true * y_pred)), 0.0)).mean(axis=(- 1))
|
def hinge(y_true, y_pred):
return T.maximum((1.0 - (y_true * y_pred)), 0.0).mean(axis=(- 1))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.