|
| 1 | +// Copyright 2020 The TensorFlow Authors. All Rights Reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import ModelSupport |
| 16 | +import Foundation |
| 17 | +import TensorFlow |
| 18 | + |
| 19 | +/// Models that comply to Checkpointable can have their Tensors be written to and read from disk |
| 20 | +/// using the `writeCheckpoint(to:...)` and `readCheckpoint(from:...)` interfaces. |
| 21 | +public protocol Checkpointable: KeyPathIterable { |
| 22 | + /// Any Tensor that should be ignored for checkpoint reading or writing, specified in |
| 23 | + /// `Type.property` syntax. For example, `["Attention.scale"]`. |
| 24 | + var ignoredTensorPaths: Set<String> { get } |
| 25 | + |
| 26 | + /// The string separator between descending levels of the model. For example, a separator of `"/"` |
| 27 | + /// will yield tensor path names like `conv2/filter`. |
| 28 | + var checkpointSeparator: String { get } |
| 29 | + |
| 30 | + /// A mapping function between the internally generated tensor path names and how those names |
| 31 | + /// will or do appear in the on-disk checkpoint. |
| 32 | + var tensorNameMap: ((String) -> String) { get } |
| 33 | +} |
| 34 | + |
| 35 | +public extension Checkpointable { |
| 36 | + var ignoredTensorPaths: Set<String> { |
| 37 | + return [] |
| 38 | + } |
| 39 | + |
| 40 | + var checkpointSeparator: String { |
| 41 | + return "/" |
| 42 | + } |
| 43 | + |
| 44 | + var tensorNameMap: (String) -> String { |
| 45 | + return CheckpointWriter.identityMap |
| 46 | + } |
| 47 | + |
| 48 | + /// Writes a checkpoint of this model's tensors to disk. |
| 49 | + /// |
| 50 | + /// - Parameters: |
| 51 | + /// - location: The directory to write the checkpoint into. If it doesn't exist, it will be |
| 52 | + /// created. |
| 53 | + /// - name: The base name of the checkpoint, which is what will have the .index and |
| 54 | + /// .data-0000X-of-0000Y extensions appended to it for files in the checkpoint directory. |
| 55 | + /// - fileSystem: The filesystem used for writing the checkpoint. Defaults to |
| 56 | + /// FoundationFileSystem. |
| 57 | + /// - nameTable: A lookup table of generated tensor path names to their corresponding tensor |
| 58 | + /// name in the checkpoint file. If an internal tensor path name is not represented, the |
| 59 | + /// internal path name is used for the on-disk checkpoint. |
| 60 | + func writeCheckpoint( |
| 61 | + to location: URL, name: String, fileSystem: FileSystem = FoundationFileSystem(), |
| 62 | + nameTable: [String: String] |
| 63 | + ) throws { |
| 64 | + try writeCheckpoint( |
| 65 | + to: location, name: name, fileSystem: fileSystem, |
| 66 | + nameMap: CheckpointWriter.lookupMap(table: nameTable)) |
| 67 | + } |
| 68 | + |
| 69 | + /// Writes a checkpoint of this model's tensors to disk. |
| 70 | + /// |
| 71 | + /// - Parameters: |
| 72 | + /// - location: The directory to write the checkpoint into. If it doesn't exist, it will be |
| 73 | + /// created. |
| 74 | + /// - name: The base name of the checkpoint, which is what will have the .index and |
| 75 | + /// .data-0000X-of-0000Y extensions appended to it for files in the checkpoint directory. |
| 76 | + /// - fileSystem: The filesystem used for writing the checkpoint. Defaults to |
| 77 | + /// FoundationFileSystem. |
| 78 | + /// - nameMap: A mapping function that converts generated tensor path names to their |
| 79 | + /// corresponding tensor name in the checkpoint file. |
| 80 | + func writeCheckpoint( |
| 81 | + to location: URL, name: String, fileSystem: FileSystem = FoundationFileSystem(), |
| 82 | + nameMap: ((String) -> String)? = nil |
| 83 | + ) throws { |
| 84 | + var rawTensors: [String: Tensor<Float>] = [:] |
| 85 | + CheckpointWriter.recursivelyObtainTensors( |
| 86 | + self, tensors: &rawTensors, separator: self.checkpointSeparator, |
| 87 | + ignoredTensorPaths: self.ignoredTensorPaths) |
| 88 | + |
| 89 | + let tensors = CheckpointWriter.remapTensorNames(tensors: rawTensors, |
| 90 | + nameMap: nameMap ?? self.tensorNameMap) |
| 91 | + |
| 92 | + let writer = CheckpointWriter(fileSystem: fileSystem) |
| 93 | + try writer.write(tensors: tensors, to: location, name: name) |
| 94 | + } |
| 95 | + |
| 96 | + /// Reads a checkpoint of this model's tensors from disk. |
| 97 | + /// |
| 98 | + /// - Parameters: |
| 99 | + /// - location: Either a URL to the checkpoint files, where the last component is the file |
| 100 | + /// base of the checkpoint files, or a URL to an archive containing the checkpoint files. |
| 101 | + /// - name: The base name of the checkpoint, which is what will have the .index and |
| 102 | + /// .data-0000X-of-0000Y extensions appended to it for files in the checkpoint directory. |
| 103 | + /// - fileSystem: The filesystem used for reading the checkpoint. Defaults to |
| 104 | + /// FoundationFileSystem. |
| 105 | + /// - nameMap: A mapping function that converts generated tensor path names to their |
| 106 | + /// corresponding tensor name in the checkpoint file. |
| 107 | + mutating func readCheckpoint( |
| 108 | + from location: URL, name: String, fileSystem: FileSystem = FoundationFileSystem(), |
| 109 | + nameMap: ((String) -> String)? = nil |
| 110 | + ) throws { |
| 111 | + var rawTensorNames: [String] = [] |
| 112 | + CheckpointReader.recursivelyObtainTensorNames( |
| 113 | + self, tensors: &rawTensorNames, separator: self.checkpointSeparator, |
| 114 | + ignoredTensorPaths: self.ignoredTensorPaths) |
| 115 | + |
| 116 | + let concreteNameMap = nameMap ?? self.tensorNameMap |
| 117 | + let tensorNames = rawTensorNames.map{ concreteNameMap($0) } |
| 118 | + |
| 119 | + let keypaths = self.recursivelyAllWritableKeyPaths(to: Tensor<Float>.self) |
| 120 | + |
| 121 | + guard keypaths.count == tensorNames.count else { |
| 122 | + fatalError( |
| 123 | + "The number of writable key paths: \(keypaths.count) did not match the number of tensor names: \(tensorNames.count)") |
| 124 | + } |
| 125 | + |
| 126 | + let reader: CheckpointReader = try CheckpointReader(checkpointLocation: location, |
| 127 | + modelName: name) |
| 128 | + |
| 129 | + for (index, keypath) in keypaths.enumerated() { |
| 130 | + self[keyPath: keypath] = Tensor<Float>(reader.loadTensor(named: tensorNames[index])) |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + /// Reads a checkpoint of this model's tensors from disk. |
| 135 | + /// |
| 136 | + /// - Parameters: |
| 137 | + /// - location: Either a URL to the checkpoint files, where the last component is the file |
| 138 | + /// base of the checkpoint files, or a URL to an archive containing the checkpoint files. |
| 139 | + /// - name: The base name of the checkpoint, which is what will have the .index and |
| 140 | + /// .data-0000X-of-0000Y extensions appended to it for files in the checkpoint directory. |
| 141 | + /// - fileSystem: The filesystem used for reading the checkpoint. Defaults to |
| 142 | + /// FoundationFileSystem. |
| 143 | + /// - nameTable: A lookup table of generated tensor path names to their corresponding tensor |
| 144 | + /// name in the checkpoint file. If an internal tensor path name is not represented, the |
| 145 | + /// internal path name is used for the on-disk checkpoint. |
| 146 | + mutating func readCheckpoint( |
| 147 | + from location: URL, name: String, fileSystem: FileSystem = FoundationFileSystem(), |
| 148 | + nameTable: [String: String] |
| 149 | + ) throws { |
| 150 | + try readCheckpoint( |
| 151 | + from: location, name: name, fileSystem: fileSystem, |
| 152 | + nameMap: CheckpointWriter.lookupMap(table: nameTable)) |
| 153 | + } |
| 154 | +} |
0 commit comments