Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EmbeddingVariable support save/restore #39

Merged
merged 2 commits into from
Mar 31, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 0 additions & 23 deletions docs/tutorials/embedding_variable_tutorial.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
},
{
"cell_type": "markdown",
"id": "architectural-blink",
"metadata": {
"id": "05cf26dc9b18"
},
Expand All @@ -43,7 +42,6 @@
},
{
"cell_type": "markdown",
"id": "surprising-glasgow",
"metadata": {
"id": "dc653218a95f"
},
Expand All @@ -53,7 +51,6 @@
},
{
"cell_type": "markdown",
"id": "otherwise-lying",
"metadata": {
"id": "ac41b69489ae"
},
Expand All @@ -64,7 +61,6 @@
{
"cell_type": "code",
"execution_count": 1,
"id": "trained-dollar",
"metadata": {
"id": "0ec04b6192ff"
},
Expand All @@ -80,7 +76,6 @@
},
{
"cell_type": "markdown",
"id": "fourth-ticket",
"metadata": {
"id": "d85a1d4753ff"
},
Expand All @@ -92,7 +87,6 @@
{
"cell_type": "code",
"execution_count": null,
"id": "arctic-topic",
"metadata": {
"id": "99940220fef6"
},
Expand All @@ -114,7 +108,6 @@
},
{
"cell_type": "markdown",
"id": "everyday-minimum",
"metadata": {
"id": "6d237ed66cb7"
},
Expand All @@ -126,7 +119,6 @@
{
"cell_type": "code",
"execution_count": 2,
"id": "applied-index",
"metadata": {
"id": "3887a87a2372"
},
Expand Down Expand Up @@ -191,7 +183,6 @@
},
{
"cell_type": "markdown",
"id": "mounted-survey",
"metadata": {
"id": "cb07cc348aea"
},
Expand All @@ -203,7 +194,6 @@
{
"cell_type": "code",
"execution_count": 3,
"id": "original-manor",
"metadata": {
"id": "e294e730c794"
},
Expand All @@ -215,7 +205,6 @@
},
{
"cell_type": "markdown",
"id": "instant-damages",
"metadata": {
"id": "6376d2a17bb5"
},
Expand All @@ -227,7 +216,6 @@
{
"cell_type": "code",
"execution_count": 4,
"id": "amino-platinum",
"metadata": {
"id": "9288e8ec77cb"
},
Expand All @@ -250,7 +238,6 @@
},
{
"cell_type": "markdown",
"id": "defined-darwin",
"metadata": {
"id": "6fb127e74992"
},
Expand All @@ -260,7 +247,6 @@
},
{
"cell_type": "markdown",
"id": "committed-quarter",
"metadata": {
"id": "a6495a6f963f"
},
Expand All @@ -272,7 +258,6 @@
{
"cell_type": "code",
"execution_count": 1,
"id": "beneficial-hepatitis",
"metadata": {
"id": "5218cb658f44"
},
Expand All @@ -290,7 +275,6 @@
},
{
"cell_type": "markdown",
"id": "brazilian-hacker",
"metadata": {
"id": "3d349f3bfc07"
},
Expand All @@ -302,7 +286,6 @@
{
"cell_type": "code",
"execution_count": null,
"id": "norwegian-broadcasting",
"metadata": {
"id": "b19e0f30dfb1"
},
Expand All @@ -324,7 +307,6 @@
},
{
"cell_type": "markdown",
"id": "dated-plant",
"metadata": {
"id": "d0031b8e091a"
},
Expand All @@ -336,7 +318,6 @@
{
"cell_type": "code",
"execution_count": 2,
"id": "sized-carolina",
"metadata": {
"id": "1b5619f1a319"
},
Expand Down Expand Up @@ -401,7 +382,6 @@
},
{
"cell_type": "markdown",
"id": "split-invention",
"metadata": {
"id": "0c27d0bbbd00"
},
Expand All @@ -413,7 +393,6 @@
{
"cell_type": "code",
"execution_count": 3,
"id": "blond-wagner",
"metadata": {
"id": "4df6f03efbda"
},
Expand All @@ -427,7 +406,6 @@
},
{
"cell_type": "markdown",
"id": "solid-provider",
"metadata": {
"id": "b8d8074c46c2"
},
Expand All @@ -439,7 +417,6 @@
{
"cell_type": "code",
"execution_count": 4,
"id": "korean-canvas",
"metadata": {
"id": "95883928d2a3"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,16 @@ class EmbeddingVar : public ResourceBase {
return Status::OK();
}

int64 GetSnapshot(std::vector<K>* key_list, std::vector<V*>* value_list) {
tf_shared_lock l(mu_);
int64 tot_size = dense_hash_map_.size();
for (const auto it : dense_hash_map_) {
key_list->push_back(it.first);
value_list->push_back(it.second);
}
return tot_size;
}

mutex* mu() { return &mu_; }

private:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -539,5 +539,88 @@ REGISTER_CPU_KERNELS(float);
#undef REGISTER_CPU_KERNELS
#undef REGISTER_KERNELS

template <typename TKey, typename TValue>
class EVExportOp : public OpKernel {
public:
explicit EVExportOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}

void Compute(OpKernelContext* ctx) {
EmbeddingVar<TKey, TValue>* ev = nullptr;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &ev));
std::vector<TKey> key_list;
std::vector<TValue*> valueptr_list;
int64 total_size = ev->GetSnapshot(&key_list, &valueptr_list);

Tensor* key = nullptr;
Tensor* val = nullptr;
OP_REQUIRES_OK(ctx,
ctx->allocate_output(0, TensorShape({total_size}), &key));
OP_REQUIRES_OK(
ctx, ctx->allocate_output(1, TensorShape({total_size, ev->ValueLen()}),
&val));
auto key_flat = key->flat<TKey>();
auto val_matrix = val->matrix<TValue>();
for (size_t i = 0; i < total_size; ++i) {
key_flat(i) = key_list[i];
TValue* value = valueptr_list[i];
Eigen::array<Eigen::DenseIndex, 1> dims({ev->ValueLen()});
typename TTypes<TValue>::Flat value_flat =
typename TTypes<TValue>::Flat(value, dims);
for (int64 j = 0; j < ev->ValueLen(); ++j) {
val_matrix(i, j) = value_flat(j);
}
}
}
};

#define REGISTER_KERNELS(ktype, vtype) \
REGISTER_KERNEL_BUILDER(Name("EVExport") \
.Device(DEVICE_CPU) \
.TypeConstraint<ktype>("Tkey") \
.TypeConstraint<vtype>("Tvalue"), \
EVExportOp<ktype, vtype>);
#define REGISTER_CPU_KERNELS(T) \
REGISTER_KERNELS(int32, T); \
REGISTER_KERNELS(int64, T);

REGISTER_CPU_KERNELS(float);

#undef REGISTER_CPU_KERNELS
#undef REGISTER_KERNELS

template <typename TKey, typename TValue>
class EVImportOp : public OpKernel {
public:
explicit EVImportOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}

void Compute(OpKernelContext* ctx) {
EmbeddingVar<TKey, TValue>* ev = nullptr;
OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &ev));
Tensor key = ctx->input(1);
Tensor val = ctx->input(2);
auto key_flat = key.flat<TKey>();
auto val_matrix = val.matrix<TValue>();
for (size_t i = 0; i < key.NumElements(); ++i) {
auto value = &val_matrix(i, 0);
ev->LookupOrCreate(key_flat(i), value);
}
}
};

#define REGISTER_KERNELS(ktype, vtype) \
REGISTER_KERNEL_BUILDER(Name("EVImport") \
.Device(DEVICE_CPU) \
.TypeConstraint<ktype>("Tkey") \
.TypeConstraint<vtype>("Tvalue"), \
EVImportOp<ktype, vtype>);
#define REGISTER_CPU_KERNELS(T) \
REGISTER_KERNELS(int32, T); \
REGISTER_KERNELS(int64, T);

REGISTER_CPU_KERNELS(float);

#undef REGISTER_CPU_KERNELS
#undef REGISTER_KERNELS

} // namespace ev
} // namespace tensorflow
Original file line number Diff line number Diff line change
Expand Up @@ -267,5 +267,23 @@ REGISTER_OP("EVSparseApplyAdam")
.Doc(R"doc(
)doc");

REGISTER_OP("EVExport")
.Input("ev: resource")
.Output("keys: Tkey")
.Output("values: Tvalue")
.Attr("Tkey: {int32, int64}")
.Attr("Tvalue: numbertype")
.Doc(R"doc(
)doc");

REGISTER_OP("EVImport")
.Input("ev: resource")
.Input("keys: Tkey")
.Input("values: Tvalue")
.Attr("Tkey: {int32, int64}")
.Attr("Tvalue: numbertype")
.Doc(R"doc(
)doc");

} // namespace ev
} // namespace tensorflow
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,16 @@
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.training.tracking import base as trackable
from tensorflow.python.util import compat
from tensorflow.python.training.saving import saveable_object
from tensorflow.python.training.saver import BaseSaverBuilder

from tensorflow_recommenders_addons.embedding_variable.python import gen_ev_ops

__all__ = ["EmbeddingVariable"]


class EmbeddingVariable(resource_variable_ops.ResourceVariable):
class EmbeddingVariable(resource_variable_ops.ResourceVariable,
saveable_object.SaveableObject):
"""Embedding Variable based on resource variable.

See the ${variables} documentation for more details.
Expand Down Expand Up @@ -341,6 +344,17 @@ def _init_from_args(self,
cached_value=cached_value,
caching_device=caching_device)

tensors = gen_ev_ops.ev_export(self.handle, Tkey=self._ktype, Tvalue=vtype)
self.specs = [
BaseSaverBuilder.SaveSpec(tensors[0], "", name + "-keys"),
BaseSaverBuilder.SaveSpec(tensors[1], "", name + "-values"),
]

def restore(self, restored_tensors, restored_shapes):
with ops.control_dependencies([self.initializer]):
return gen_ev_ops.ev_import(self.handle, restored_tensors[0],
restored_tensors[1])

def _init_from_proto(self, variable_def, import_scope=None):
"""Initializes from `VariableDef` proto."""
# Note that init_from_proto is currently not supported in Eager mode.
Expand Down Expand Up @@ -465,7 +479,6 @@ def to_proto(self, export_scope=None):
var_def.snapshot_name = ops.strip_name_scope(self._cached_value.name,
export_scope)
var_def.is_resource = True
var_def.is_embedding_var = True
if self._save_slice_info:
var_def.save_slice_info_def.MergeFrom(
self._save_slice_info.to_proto(export_scope=export_scope))
Expand Down
Loading