EmbeddingVariable

Updated at:

EmbeddingVariable is a variable type that PAI-TensorFlow provides for training on large-scale sparse features. It implements dynamic embedding semantics: the vocabulary size grows with training instead of being fixed in advance, so no memory is reserved for IDs that are never looked up. EmbeddingVariable keeps features lossless, which allows you to run offline training on large-scale features and bring the model online.

Note

GPU-accelerated servers will be phased out. You can submit TensorFlow tasks that run on CPU servers. If you want to use GPU-accelerated instances for model training, go to Deep Learning Containers (DLC) to submit jobs. For more information, see Create a training job.

Embeddings in TensorFlow

TensorFlow implements the embedding mechanism by using Variables. The space size of the Variable that stores an embedding is [vocabulary_size, embedding_dimension], and that space size is fixed when you define the Variable. This design limits what a Variable can express in large-scale sparse feature scenarios.

Embedding is an effective way to process word features and ID features in deep learning. As a function mapping, embedding applies feature mapping to convert high-dimensional sparse features into low-dimensional dense vectors, which are then used for end-to-end model training. In TensorFlow, you use a Variable to define a model or a node state, and the implementation of the Variable relies on the Tensor data structure. A Tensor uses contiguous storage. Therefore, when you define a Variable, you must specify the type (Type) and the space size (Shape), and the space size cannot be modified.

A Tensor is the abstract data type of TensorFlow, and it covers scalars, vectors, matrices, and higher-dimensional data structures. A Tensor carries data between operators, and any operator that accepts a Tensor as its input and output can join the computation of a Graph.

In large-scale sparse feature scenarios, an embedding that is stored in a Variable has the following drawbacks:

  • Vocabulary size is hard to estimate — vocabulary_size is determined by the ID space. As the number of IDs keeps growing in online learning scenarios, vocabulary_size becomes difficult to estimate.

  • Hashing forces a trade-off — IDs are usually strings and large in scale. Before embedding, you must hash the IDs into the vocabulary_size range:

    • If vocabulary_size is too small, the hash collision rate increases, and different features may look up the same embedding. As a result, the number of effective features decreases.

    • If vocabulary_size is too large, the Variable stores embeddings that are never looked up. As a result, memory is wasted.

  • Embeddings cannot be removed — Oversized embeddings are the main cause of model size growth. Even if you use regularization to reduce the impact of the embeddings of specific features on the overall model, you cannot remove those embeddings from the model.

To resolve the preceding issues, PAI-TensorFlow provides EmbeddingVariable, which implements dynamic embedding semantics. Feature training stays lossless, and because the vocabulary size follows training, memory is not reserved for IDs that are never looked up. You can therefore run offline training on large-scale features and bring the model online.

EmbeddingVariable capabilities

  • Dynamic embedding — You do not need to specify the vocabulary size. You only need to specify the embedding dimension, and PAI-TensorFlow dynamically adjusts the vocabulary size based on training. This applies to online learning scenarios and also removes the data pre-processing step that TensorFlow models require.

  • Group lasso regularization — Embeddings produced by deep learning are usually very large, and deploying such variables as an online service puts the serving hosts under load. If you apply group lasso regularization to embeddings, you reduce the load that model deployment places on those hosts.

  • Lossless feature input — EmbeddingVariable accepts original feature values in the embedding lookup. This removes hashing and other ID conversion operations, which achieves lossless feature training.

  • Graph participation — EmbeddingVariable supports Graph inference and backpropagation.

  • Import and export — EmbeddingVariable supports the import and export of variables.

  • Automatic updates — During model training, the optimizer updates the EmbeddingVariable automatically.

Limits

Before you build a Graph that contains an EmbeddingVariable, review the following constraints:

  • Supported optimizers — EmbeddingVariable supports only the Ftrl Optimizer, Adagrad Optimizer, Adam Optimizer, and AdagradDecay Optimizer.

  • Version-restricted parameters — The steps_to_live_l2reg and l2reg_theta parameters of tf.contrib.layers.sparse_column_with_embedding are not supported in version 1120. They are supported only in version 140lite.

APIs for creating an EmbeddingVariable

PAI-TensorFlow provides two APIs that create an EmbeddingVariable: the Feature_Column API and the EmbeddingVariable API. Use the Feature_Column API by default, because it automatically adds the feature ID conversion process for strings. The EmbeddingVariable API, tf.get_embedding_variable, is the low-level alternative and returns an existing or newly created EmbeddingVariable.

The Feature_Column API (recommended)

tf.contrib.layers.sparse_column_with_embedding creates a sparse column that is backed by an EmbeddingVariable. The signature is as follows.

tf.contrib.layers.sparse_column_with_embedding(column_name=column_name,
                                               dtype=tf.string,
                                               partition_num=None,
                                               steps_to_live=None,
                                               # The following two parameters are not supported in version 1120. They are supported only in version 140lite.
                                               steps_to_live_l2reg=None,
                                               l2reg_theta=None)
  • column_name: the name of the column.

  • dtype: the type of the column. Default value: tf.string.

  • partition_num

  • steps_to_live

  • steps_to_live_l2reg and l2reg_theta: not supported in version 1120. Supported only in version 140lite.

The following example uses the feature_column API to build a TensorFlow Graph that contains an EmbeddingVariable.

import tensorflow as tf
import os

columns_list=[]
columns_list.append(tf.contrib.layers.sparse_column_with_embedding(column_name="col_emb", dtype=tf.string))
W = tf.contrib.layers.shared_embedding_columns(sparse_id_columns=columns_list,
        dimension=3,
        initializer=tf.ones_initializer(tf.float32),
        shared_embedding_name="xxxxx_shared")

ids={}
ids["col_emb"] = tf.SparseTensor(indices=[[0,0],[1,0],[2,0],[3,0],[4,0]], values=["aaaa","bbbbb","ccc","4nn","5b"], dense_shape=[5, 5])

emb = tf.contrib.layers.input_from_feature_columns(columns_to_tensors=ids, feature_columns=W)

fun = tf.multiply(emb, 2.0, name='multiply')
loss = tf.reduce_sum(fun, name='reduce_sum')
opt = tf.train.FtrlOptimizer(0.1, l1_regularization_strength=2.0, l2_regularization_strength=0.00001)
g_v = opt.compute_gradients(loss)
train_op = opt.apply_gradients(g_v)
init = tf.global_variables_initializer()
init_local = tf.local_variables_initializer()
sess_config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)
with tf.Session(config=sess_config) as sess:
  sess.run(init)
  print("init global done")
  sess.run(init_local)
  print("init local done")
  print(sess.run([emb, train_op,loss]))
  print(sess.run([emb, train_op,loss]))
  print(sess.run([emb, train_op,loss]))
  print(sess.run([emb]))

The tf.get_embedding_variable API

The tf.get_embedding_variable API returns an existing or newly created EmbeddingVariable. The API is defined as follows.

get_embedding_variable(
    name,
    embedding_dim,
    key_dtype=dtypes.int64,
    value_dtype=None,
    initializer=None,
    trainable=True,
    collections=None,
    partitioner=None,
    custom_getter=None,
    steps_to_live=None,
    filter_options=variables.CounterFilterOptions()
)
ParameterDescription
nameThe name of the EmbeddingVariable.
embedding_dimThe dimension of the embedding. Example: 8 or 64.
key_dtypeThe type of the key used in a lookup. Default value: int64.
value_dtypeThe type of the EmbeddingVariable. Only float is supported.
initializerThe initial value of the EmbeddingVariable.
trainableSpecifies whether the variable is added to the collection of GraphKeys.TRAINABLE_VARIABLES.
collectionsA list that records the keys of collections. The variable is added to the collections in the list. Default value: [GraphKeys.GLOBAL_VARIABLES].
partitionerThe partition function.
custom_getterA callable object that takes the true getter as its first parameter and can override the internal get_variable method. It must conform to the def custom_getter(getter,*args,**kwargs) form. To directly access all parameters in get_variable, use the def custom_getter(getter,name,*args,**kwargs) form.
steps_to_liveThe eviction threshold, expressed in global steps. The system deletes features that have not been updated for more global steps than the value of this parameter.
filter_optionsThe admission policy. Admission based on feature frequency is supported.

The following example uses the low-level tf.get_embedding_variable API to build a TensorFlow Graph that contains an EmbeddingVariable.

#!/usr/bin/python
import tensorflow as tf

var = tf.get_embedding_variable("var_0",
                                embedding_dim=3,
                                initializer=tf.ones_initializer(tf.float32),
                                partitioner=tf.fixed_size_partitioner(num_shards=4))

shape = [var1.total_count() for var1 in var]

emb = tf.nn.embedding_lookup(var, tf.cast([0,1,2,5,6,7], tf.int64))
fun = tf.multiply(emb, 2.0, name='multiply')
loss = tf.reduce_sum(fun, name='reduce_sum')
opt = tf.train.FtrlOptimizer(0.1,
                             l1_regularization_strength=2.0,
                             l2_regularization_strength=0.00001)

g_v = opt.compute_gradients(loss)
train_op = opt.apply_gradients(g_v)

init = tf.global_variables_initializer()

sess_config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)
with tf.Session(config=sess_config) as sess:
  sess.run([init])
  print(sess.run([emb, train_op, loss]))
  print(sess.run([emb, train_op, loss]))
  print(sess.run([emb, train_op, loss]))
  print(sess.run([shape]))

EmbeddingVariable class reference

The structure of EmbeddingVariable is as follows.

class EmbeddingVariable(ResourceVariable)

  def total_count():
    # Returns the current total_count of the embedding, [rowCount, EmbeddingDim].
  def read_value():
    raise NotImplementedError("...")
  def assign():
    raise NotImplementedError("...")
  def assign_add():
    raise NotImplementedError("...")
  def assign_sub():
    raise NotImplementedError("...")

Method support

MethodSupportDescription
sparse_read()SupportedReads sparse data. If the queried key does not exist, the initializer that corresponds to the key during EmbeddingVariable initialization is returned.
total_count()SupportedQueries the total number of entries in the EmbeddingVariable vocabulary. This method returns the dynamic Shape value of the EmbeddingVariable.
read_value()Not supportedReads the entire EmbeddingVariable.
assign(), assign_add(), assign_sub()Not supportedThe assignment methods of EmbeddingVariable.

CounterFilterOptions

CounterFilterOptions carries the admission policy that you pass to the filter_options parameter. The structure is as follows.

@tf_export("CounterFilterOptions")
class CounterFilterOptions(object):
    def __init__(self, filter_freq=0):
        pass

filter_freq specifies the admission frequency. Default value: 0.

Checkpoint save and restore

EmbeddingVariable supports the import and export of variables, so tf.train.Saver saves an EmbeddingVariable to a checkpoint and restores it from that checkpoint. The restore example reads model.ckpt-666, which the save example writes when it saves with global_step=666.

Saving an EmbeddingVariable to a checkpoint

#!/usr/bin/python
import tensorflow as tf

var = tf.get_embedding_variable("var_0",
                                embedding_dim=3,
                                initializer=tf.ones_initializer(tf.float32),
                                partitioner=tf.fixed_size_partitioner(num_shards=4))

emb = tf.nn.embedding_lookup(var, tf.cast([0,1,2,5,6,7], tf.int64))

init = tf.global_variables_initializer()
saver = tf.train.Saver(sharded=True)
print("GLOBAL_VARIABLES: ", tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES))
print("SAVEABLE_OBJECTS: ", tf.get_collection(tf.GraphKeys.SAVEABLE_OBJECTS))

checkpointDir = "/tmp/model_dir"
sess_config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)
with tf.Session(config=sess_config) as sess:
  sess.run([init])
  print(sess.run([emb]))

  save_path = saver.save(sess, checkpointDir + "/model.ckpt", global_step=666)
  tf.train.write_graph(sess.graph_def, checkpointDir, 'train.pbtxt')
  print("save_path", save_path)
  print("list_variables", tf.contrib.framework.list_variables(checkpointDir))

Restoring an EmbeddingVariable from a checkpoint

#!/usr/bin/python
import tensorflow as tf

var = tf.get_embedding_variable("var_0",
                                embedding_dim=3,
                                initializer=tf.ones_initializer(tf.float32),
                                partitioner=tf.fixed_size_partitioner(num_shards=4))

emb = tf.nn.embedding_lookup(var, tf.cast([0,1,2,5,6,7], tf.int64))

init = tf.global_variables_initializer()
saver = tf.train.Saver(sharded=True)
print("GLOBAL_VARIABLES: ", tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES))
print("SAVEABLE_OBJECTS: ", tf.get_collection(tf.GraphKeys.SAVEABLE_OBJECTS))

checkpointDir = "/tmp/model_dir"
sess_config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)
with tf.Session(config=sess_config) as sess:
  print("list_variables", tf.contrib.framework.list_variables(checkpointDir))
  saver.restore(sess, checkpointDir + "/model.ckpt-666")
  print(sess.run([emb]))