|
| 1 | +/* Copyright © 2020 Apple Inc. All rights reserved. |
| 2 | + * |
| 3 | + * Use of this source code is governed by a BSD-3-clause license that can |
| 4 | + * be found in the LICENSE.txt file or at |
| 5 | + * https://opensource.org/licenses/BSD-3-Clause |
| 6 | + */ |
| 7 | +#include <toolkits/util/float_array_serialization.hpp> |
| 8 | + |
| 9 | +namespace turi { |
| 10 | + |
| 11 | +using neural_net::float_array_map; |
| 12 | +using neural_net::shared_float_array; |
| 13 | + |
| 14 | +class float_array_serialization_wrapper { |
| 15 | + public: |
| 16 | + float_array_serialization_wrapper() = default; |
| 17 | + explicit float_array_serialization_wrapper(shared_float_array array) |
| 18 | + : impl_(std::move(array)) {} |
| 19 | + |
| 20 | + const shared_float_array& get() const { return impl_; } |
| 21 | + |
| 22 | + void save(oarchive& oarc) const { |
| 23 | + // Write shape. |
| 24 | + serialize_iterator(oarc, impl_.shape(), impl_.shape() + impl_.dim(), |
| 25 | + impl_.dim()); |
| 26 | + |
| 27 | + // Write data. |
| 28 | + serialize_iterator(oarc, impl_.data(), impl_.data() + impl_.size(), |
| 29 | + impl_.size()); |
| 30 | + } |
| 31 | + |
| 32 | + void load(iarchive& iarc) { |
| 33 | + // Read shape. |
| 34 | + std::vector<size_t> shape; |
| 35 | + iarc >> shape; |
| 36 | + |
| 37 | + // Read data. |
| 38 | + std::vector<float> data; |
| 39 | + iarc >> data; |
| 40 | + |
| 41 | + // Overwrite self with a new float_array wrapping the deserialized data. |
| 42 | + impl_ = shared_float_array::wrap(std::move(data), std::move(shape)); |
| 43 | + } |
| 44 | + |
| 45 | + private: |
| 46 | + shared_float_array impl_; |
| 47 | +}; |
| 48 | + |
| 49 | +void save_float_array_map(const float_array_map& weights, oarchive& oarc) { |
| 50 | + // Wrap each shared_float_array in weights in a wrapper that knows how to |
| 51 | + // write itself to the oarchive. |
| 52 | + std::map<std::string, float_array_serialization_wrapper> wrapped_weights; |
| 53 | + for (const auto& key_value : weights) { |
| 54 | + wrapped_weights[key_value.first] = |
| 55 | + float_array_serialization_wrapper(key_value.second); |
| 56 | + } |
| 57 | + |
| 58 | + oarc << wrapped_weights; |
| 59 | +} |
| 60 | + |
| 61 | +float_array_map load_float_array_map(iarchive& iarc) { |
| 62 | + // Read the iarchive into wrappers around the underlying weights. |
| 63 | + std::map<std::string, float_array_serialization_wrapper> wrapped_weights; |
| 64 | + iarc >> wrapped_weights; |
| 65 | + |
| 66 | + // Obtain direct references to the underlying weights. |
| 67 | + float_array_map weights; |
| 68 | + for (const auto& key_value : wrapped_weights) { |
| 69 | + weights[key_value.first] = key_value.second.get(); |
| 70 | + } |
| 71 | + |
| 72 | + return weights; |
| 73 | +} |
| 74 | + |
| 75 | +} // namespace turi |
0 commit comments