Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 489 lines (390 sloc) 17.6 KB
# Copyright 2016 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# See the License for the specific language governing permissions and
# limitations under the License.
"""Submatrix-wise Vector Embedding Learner.
Implementation of SwiVel algorithm described at:
This program expects an input directory that contains the following files.
row_vocab.txt, col_vocab.txt
The row an column vocabulary files. Each file should contain one token per
line; these will be used to generate a tab-separate file containing the
trained embeddings.
row_sums.txt, col_sum.txt
The matrix row and column marginal sums. Each file should contain one
decimal floating point number per line which corresponds to the marginal
count of the matrix for that row or column.
A file containing the sub-matrix shards, stored as TFRecords. Each shard is
expected to be a serialzed tf.Example protocol buffer with the following
global_row: the global row indicies contained in the shard
global_col: the global column indicies contained in the shard
sparse_local_row, sparse_local_col, sparse_value: three parallel arrays
that are a sparse representation of the submatrix counts.
It will generate embeddings, training from the input directory for the specified
number of epochs. When complete, it will output the trained vectors to a
tab-separated file that contains one line per embedding. Row and column
embeddings are stored in separate files.
Swivel can be run "stand-alone" or "distributed". The latter involves running
at least one parameter server process, along with one or more worker processes.
from __future__ import division
from __future__ import print_function
import glob
import itertools
import os
import random
import numpy as np
import scipy.stats
import tensorflow as tf
flags =
'input_base_path', '/tmp/swivel_data',
'Directory containing input shards, vocabularies, and marginals.')
'output_base_path', '/tmp/swivel_data',
'Path where to write the trained embeddings.')
flags.DEFINE_string('eval_base_path', '', 'Path to evaluation data')
# Control for training.
flags.DEFINE_float('num_epochs', 40, 'Number epochs to train')
flags.DEFINE_string('hparams', '', 'Model hyper-parameters')
# Model hyper-parameters. (Move these to tf.HParams once that gets integrated
# into TF from tf.contrib.)
'dim', 300, 'Embedding dimensionality')
'optimizer', 'rmsprop', 'SGD optimizer; either "adagrad" or "rmsprop"')
'learning_rate', 0.1, 'Optimizer learning rate')
'momentum', 0.1, 'Optimizer momentum; used with RMSProp')
'confidence_base', 0.0, 'Base for count weighting')
'confidence_scale', 1.0, 'Scale for count weighting')
'confidence_exponent', 0.5, 'Exponent for count weighting')
'submatrix_rows', 4096, 'Number of rows in each submatrix')
'submatrix_cols', 4096, 'Number of cols in each submatrix')
# For distributed training.
'ps_hosts', '',
'Comma-separated list of parameter server host:port; if empty, run local')
'worker_hosts', '', 'Comma-separated list of worker host:port')
'job_name', '', 'The job this process will run, either "ps" or "worker"')
'task_index', 0, 'The task index for this process')
'gpu_device', 0, 'The GPU device to use.')
class Model(object):
"""A Swivel model."""
def __init__(self, input_base_path, hparams):
"""Creates a new Swivel model."""
# Read vocab
self.row_ix_to_word, self.row_word_to_ix = self._read_vocab(
os.path.join(input_base_path, 'row_vocab.txt'))
self.col_ix_to_word, self.col_word_to_ix = self._read_vocab(
os.path.join(input_base_path, 'col_vocab.txt'))
# Read marginals.
row_sums = self._read_marginals_file(
os.path.join(input_base_path, 'row_sums.txt'))
col_sums = self._read_marginals_file(
os.path.join(input_base_path, 'col_sums.txt'))
# Construct input tensors.
count_matrix_files = glob.glob(
os.path.join(input_base_path, 'shard-*.pb'))
global_rows, global_cols, counts = self._count_matrix_input(
count_matrix_files, hparams.submatrix_rows, hparams.submatrix_cols)
# Create embedding variables.
sigma = 1.0 / np.sqrt(hparams.dim)
self.row_embedding = tf.get_variable(
shape=[len(row_sums), hparams.dim],
initializer=tf.random_normal_initializer(0, sigma),
self.col_embedding = tf.get_variable(
shape=[len(col_sums), hparams.dim],
initializer=tf.random_normal_initializer(0, sigma),
matrix_log_sum = np.log(np.sum(row_sums) + 1)
row_bias = tf.constant(
[np.log(x + 1) for x in row_sums], dtype=tf.float32)
col_bias = tf.constant(
[np.log(x + 1) for x in col_sums], dtype=tf.float32)
# Fetch embeddings.
selected_rows = tf.nn.embedding_lookup(self.row_embedding, global_rows)
selected_cols = tf.nn.embedding_lookup(self.col_embedding, global_cols)
selected_row_bias = tf.gather(row_bias, global_rows)
selected_col_bias = tf.gather(col_bias, global_cols)
predictions = tf.matmul(selected_rows, selected_cols, transpose_b=True)
# These binary masks separate zero from non-zero values.
count_is_nonzero = tf.to_float(tf.cast(counts, tf.bool))
count_is_zero = 1 - count_is_nonzero
objectives = count_is_nonzero * tf.log(counts + 1e-30)
objectives -= tf.reshape(selected_row_bias, [-1, 1])
objectives -= selected_col_bias
objectives += matrix_log_sum
err = predictions - objectives
# The confidence function scales the L2 loss based on the raw
# co-occurrence count.
l2_confidence = (hparams.confidence_base +
hparams.confidence_scale * tf.pow(
counts, hparams.confidence_exponent))
loss_multiplier = 1 / np.sqrt(
hparams.submatrix_rows * hparams.submatrix_cols)
l2_loss = loss_multiplier * tf.reduce_sum(
0.5 * l2_confidence * tf.square(err))
sigmoid_loss = loss_multiplier * tf.reduce_sum(
tf.nn.softplus(err) * count_is_zero)
self.loss_op = l2_loss + sigmoid_loss
if hparams.optimizer == 'adagrad':
opt = tf.train.AdagradOptimizer(hparams.learning_rate)
elif hparams.optimizer == 'rmsprop':
opt = tf.train.RMSPropOptimizer(hparams.learning_rate, hparams.momentum)
raise ValueError('unknown optimizer "%s"' % hparams.optimizer)
self.global_step = tf.get_variable(
'global_step', initializer=0, trainable=False)
self.train_op = opt.minimize(self.loss_op, global_step=self.global_step)
# One epoch trains each submatrix once.
self.steps_per_epoch = (
(len(row_sums) / hparams.submatrix_rows) *
(len(col_sums) / hparams.submatrix_cols))
def _read_vocab(self, filename):
"""Reads the vocabulary file."""
with open(filename) as lines:
ix_to_word = [line.strip() for line in lines]
word_to_ix = {word: ix for ix, word in enumerate(ix_to_word)}
return ix_to_word, word_to_ix
def _read_marginals_file(self, filename):
"""Reads text file with one number per line to an array."""
with open(filename) as lines:
return [float(line.strip()) for line in lines]
def _count_matrix_input(self, filenames, submatrix_rows, submatrix_cols):
"""Creates ops that read submatrix shards from disk."""
filename_queue = tf.train.string_input_producer(filenames)
reader = tf.WholeFileReader()
_, serialized_example =
features = tf.parse_single_example(
'global_row': tf.FixedLenFeature([submatrix_rows], dtype=tf.int64),
'global_col': tf.FixedLenFeature([submatrix_cols], dtype=tf.int64),
'sparse_local_row': tf.VarLenFeature(dtype=tf.int64),
'sparse_local_col': tf.VarLenFeature(dtype=tf.int64),
'sparse_value': tf.VarLenFeature(dtype=tf.float32)
global_row = features['global_row']
global_col = features['global_col']
sparse_local_row = features['sparse_local_row'].values
sparse_local_col = features['sparse_local_col'].values
sparse_count = features['sparse_value'].values
sparse_indices = tf.concat(
axis=1, values=[tf.expand_dims(sparse_local_row, 1),
tf.expand_dims(sparse_local_col, 1)])
count = tf.sparse_to_dense(sparse_indices, [submatrix_rows, submatrix_cols],
return global_row, global_col, count
def wordsim_eval_op(self, filename):
"""Returns an op that runs an eval on a word similarity dataset.
The eval dataset is assumed to be tab-separated, one scored word pair per
line. The resulting value is Spearman's rho of the human judgements with
the cosine similarity of the word embeddings.
filename: the filename containing the word similarity data.
An operator that will compute Spearman's rho of the current row
with open(filename, 'r') as fh:
tuples = (line.strip().split('\t') for line in
word1s, word2s, sims = zip(*tuples)
actuals = map(float, sims)
v1s_t = tf.nn.embedding_lookup(
[self.row_word_to_ix.get(w, 0) for w in word1s])
v2s_t = tf.nn.embedding_lookup(
[self.row_word_to_ix.get(w, 0) for w in word2s])
# Compute the predicted word similarity as the cosine similarity between the
# embedding vectors.
preds_t = tf.reduce_sum(
tf.nn.l2_normalize(v1s_t, dim=1) * tf.nn.l2_normalize(v2s_t, dim=1),
def _op(preds):
rho, _ = scipy.stats.spearmanr(preds, actuals)
return rho
return tf.py_func(_op, [preds_t], tf.float64)
def analogy_eval_op(self, filename, max_vocab_size=20000):
"""Returns an op that runs an eval on an analogy dataset.
The eval dataset is assumed to be tab-separated, with four tokens per
line. The first three tokens are query terms, the last is the expected
answer. For each line (e.g., "man king woman queen"), the vectors
corresponding to the query terms are added ("king - man + woman") to produce
a query vector. If the expected answer's vector is the nearest neighbor to
the query vector (not counting any of the query vectors themselves), then
the line is scored as correct. The reported accuracy is the number of
correct rows divided by the total number of rows. Missing terms are
replaced with an arbitrary vector and will almost certainly result in
incorrect answers.
Note that the results are approximate: for efficiency's sake, only the first
`max_vocab_size` terms are included in the nearest neighbor search.
filename: the filename containing the analogy data.
max_vocab_size: the maximum number of tokens to include in the nearest
neighbor search. By default, 20000.
The accuracy on the analogy task.
analogy_ixs = []
with open(filename, 'r') as lines:
for line in lines:
parts = line.strip().split('\t')
if len(parts) == 4:
analogy_ixs.append([self.row_word_to_ix.get(w, 0) for w in parts])
# man:king :: woman:queen => king - man + woman == queen
ix1s, ix2s, ix3s, _ = zip(*analogy_ixs)
v1s_t, v2s_t, v3s_t = (
tf.nn.embedding_lookup(self.row_embedding, ixs),
for ixs in (ix1s, ix2s, ix3s))
preds_t = v2s_t - v1s_t + v3s_t
# Compute the nearest neighbors as the cosine similarity. We only consider
# up to max_vocab_size to avoid a matmul that swamps the machine.
sims_t = tf.matmul(
tf.nn.l2_normalize(self.row_embedding[:max_vocab_size], dim=1),
# Take the four nearest neighbors, since the eval explicitly discards the
# query terms.
_, preds_ixs_t = tf.nn.top_k(sims_t, 4)
def _op(preds_ixs):
correct, total = 0, 0
for pred_ixs, actual_ixs in itertools.izip(preds_ixs, analogy_ixs):
pred_ixs = [ix for ix in pred_ixs if ix not in actual_ixs[:3]]
correct += pred_ixs[0] == actual_ixs[3]
total += 1
return correct / total
return tf.py_func(_op, [preds_ixs_t], tf.float64)
def _write_tensor(self, vocab_path, output_path, session, embedding):
"""Writes tensor to output_path as tsv."""
embeddings =
with open(output_path, 'w') as out_f:
with open(vocab_path) as vocab_f:
for index, word in enumerate(vocab_f):
word = word.strip()
embedding = embeddings[index]
print('\t'.join([word.strip()] + [str(x) for x in embedding]),
def write_embeddings(self, config, session):
"""Writes row and column embeddings disk."""
os.path.join(config.input_base_path, 'row_vocab.txt'),
os.path.join(config.output_base_path, 'row_embedding.tsv'),
session, self.row_embedding)
os.path.join(config.input_base_path, 'col_vocab.txt'),
os.path.join(config.output_base_path, 'col_embedding.tsv'),
session, self.col_embedding)
def main(_):
# If we have ps_hosts, then we'll assume that this is going to be a
# distributed training run. Configure the cluster appropriately. Otherwise,
# we just do everything in-process.
if FLAGS.ps_hosts:
cluster = tf.train.ClusterSpec({
'ps': FLAGS.ps_hosts.split(','),
'worker': FLAGS.worker_hosts.split(','),
if FLAGS.job_name == 'ps':
# Ignore the GPU if we're the parameter server. This let's the PS run on
# the same machine as a worker.
config = tf.ConfigProto(device_count={'GPU': 0})
elif FLAGS.job_name == 'worker':
config = tf.ConfigProto(gpu_options=tf.GPUOptions(
visible_device_list='%d' % FLAGS.gpu_device,
raise ValueError('unknown job name "%s"' % FLAGS.job_name)
server = tf.train.Server(
if FLAGS.job_name == 'ps':
return server.join()
device_setter = tf.train.replica_device_setter(
worker_device='/job:worker/task:%d' % FLAGS.task_index,
server = None
device_setter = tf.train.replica_device_setter(0)
# Build the graph.
with tf.Graph().as_default():
with tf.device(device_setter):
model = Model(FLAGS.input_base_path, FLAGS)
# If an eval path is present, then create eval operators and set up scalar
# summaries to report on the results. Run the evals on the CPU since
# the analogy eval requires a fairly enormous tensor to be allocated to
# do the nearest neighbor search.
if FLAGS.eval_base_path:
wordsim_filenames = glob.glob(
os.path.join(FLAGS.eval_base_path, '*'))
for filename in wordsim_filenames:
name = os.path.basename(filename).split('.')[0]
with tf.device(tf.DeviceSpec(device_type='CPU')):
op = model.wordsim_eval_op(filename)
tf.summary.scalar(name, op)
analogy_filenames = glob.glob(
os.path.join(FLAGS.eval_base_path, '*'))
for filename in analogy_filenames:
name = os.path.basename(filename).split('.')[0]
with tf.device(tf.DeviceSpec(device_type='CPU')):
op = model.analogy_eval_op(filename)
tf.summary.scalar(name, op)
tf.summary.scalar('loss', model.loss_op)
# Train on, soldier.
supervisor = tf.train.Supervisor(
is_chief=(FLAGS.task_index == 0),
max_step = FLAGS.num_epochs * model.steps_per_epoch
master = if server else ''
with supervisor.managed_session(master) as session:
local_step = 0
global_step =
while not supervisor.should_stop() and global_step < max_step:
global_step, loss, _ =[
model.global_step, model.loss_op, model.train_op])
if not np.isfinite(loss):
raise ValueError('non-finite cost at step %d' % global_step)
local_step += 1
if local_step % 10 == 0:
'local_step=%d global_step=%d loss=%.1f, %.1f%% complete',
local_step, global_step, loss, 100.0 * global_step / max_step)
if FLAGS.task_index == 0:
session, supervisor.save_path, global_step=global_step)
model.write_embeddings(FLAGS, session)
if __name__ == '__main__':
You can’t perform that action at this time.