|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | +# All rights reserved. |
| 4 | +# |
| 5 | +# This source code is licensed under the BSD-style license found in the |
| 6 | +# LICENSE file in the root directory of this source tree. |
| 7 | + |
| 8 | +#!/usr/bin/env python3 |
| 9 | + |
| 10 | +from typing import Type |
| 11 | + |
| 12 | +from torch import nn |
| 13 | +from torchrec.ir.types import SerializerInterface |
| 14 | + |
| 15 | + |
| 16 | +# TODO: Replace the default interface with the python dataclass interface |
| 17 | +DEFAULT_SERIALIZER_CLS = SerializerInterface |
| 18 | + |
| 19 | + |
| 20 | +def serialize_embedding_modules( |
| 21 | + model: nn.Module, |
| 22 | + serializer_cls: Type[SerializerInterface] = DEFAULT_SERIALIZER_CLS, |
| 23 | +) -> nn.Module: |
| 24 | + for _, module in model.named_modules(): |
| 25 | + if type(module) in serializer_cls.module_to_serializer_cls: |
| 26 | + serialized_module = serializer_cls.serialize(module) |
| 27 | + module.register_buffer("ir_metadata", serialized_module, persistent=False) |
| 28 | + |
| 29 | + return model |
| 30 | + |
| 31 | + |
| 32 | +def deserialize_embedding_modules( |
| 33 | + model: nn.Module, |
| 34 | + serializer_cls: Type[SerializerInterface] = DEFAULT_SERIALIZER_CLS, |
| 35 | +) -> nn.Module: |
| 36 | + fqn_to_new_module = {} |
| 37 | + for name, module in model.named_modules(): |
| 38 | + if "ir_metadata" in dict(module.named_buffers()): |
| 39 | + serialized_module = dict(module.named_buffers())["ir_metadata"] |
| 40 | + deserialized_module = serializer_cls.deserialize(serialized_module) |
| 41 | + fqn_to_new_module[name] = deserialized_module |
| 42 | + |
| 43 | + for fqn, new_module in fqn_to_new_module.items(): |
| 44 | + setattr(model, fqn, new_module) |
| 45 | + |
| 46 | + return model |
0 commit comments