Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/onnx/model_container.py: 74%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

167 statements  

1# Copyright (c) ONNX Project Contributors 

2# 

3# SPDX-License-Identifier: Apache-2.0 

4"""Implements function make_large_model to easily create and save models 

5bigger than 2 Gb. 

6""" 

7 

8from __future__ import annotations 

9 

10import os 

11import sys 

12from typing import TYPE_CHECKING, Any 

13 

14import numpy as np 

15 

16import onnx 

17import onnx.external_data_helper as ext_data 

18import onnx.helper 

19 

20if TYPE_CHECKING: 

21 from collections.abc import Iterable 

22 

23 

24def _set_external_data( 

25 tensor: onnx.TensorProto, 

26 location: str, 

27 offset: int | None = None, 

28 length: int | None = None, 

29 checksum: str | None = None, 

30 basepath: str | None = None, 

31) -> None: 

32 del tensor.external_data[:] 

33 tensor.data_location = onnx.TensorProto.EXTERNAL 

34 for k, v in { 

35 "location": location, 

36 "offset": offset, 

37 "length": length, 

38 "checksum": checksum, 

39 "basepath": basepath, 

40 }.items(): 

41 if v is not None: 

42 entry = tensor.external_data.add() 

43 entry.key = k 

44 entry.value = str(v) 

45 

46 

47def _enumerate_subgraphs(graph): 

48 for node in graph.node: 

49 for att in node.attribute: 

50 if att.HasField("g"): 

51 yield att.g 

52 yield from _enumerate_subgraphs(att.g) 

53 for sub_g in att.graphs: 

54 yield sub_g 

55 yield from _enumerate_subgraphs(sub_g) 

56 

57 

58def make_large_tensor_proto( 

59 location: str, tensor_name: str, tensor_type: int, shape: tuple[int, ...] 

60) -> onnx.TensorProto: 

61 """Create an external tensor. 

62 

63 Arguments: 

64 location: unique identifier (not necessary a path) 

65 tensor_name: tensor name in the graph 

66 tensor_type: onnx type 

67 shape: shape the of the initializer 

68 

69 Returns: 

70 the created tensor 

71 """ 

72 tensor_location = location 

73 tensor = onnx.TensorProto() 

74 tensor.name = tensor_name 

75 _set_external_data(tensor, tensor_location) 

76 tensor.data_type = tensor_type 

77 tensor.dims.extend(shape) 

78 return tensor 

79 

80 

81class ModelContainer: 

82 """Implements an API to store large tensors outside the main ModelProto, 

83 it avoids copying large initializers when defining the model and these initializers 

84 are never serialized through protobuf. 

85 No tensor is stored on disk until the user explicitly saves the model. 

86 """ 

87 

88 def __init__(self) -> None: 

89 self.model_proto_: onnx.ModelProto | None = None 

90 self.large_initializers: dict[str, np.ndarray] = {} 

91 

92 def check_model(self): 

93 if self.model_proto is not None: 

94 onnx.checker.check_model(self.model_proto) 

95 

96 def __getitem__(self, name: str) -> np.ndarray: 

97 """Returns an external tensor given its name.""" 

98 if name not in self.large_initializers: 

99 raise ValueError( 

100 f"Unable to find large tensor {name!r} among {sorted(self.large_initializers)}." 

101 ) 

102 return self.large_initializers[name] 

103 

104 @property 

105 def model_proto(self) -> onnx.ModelProto: 

106 if self.model_proto_ is None: 

107 raise RuntimeError("ModelContainer is empty.") 

108 return self.model_proto_ 

109 

110 @model_proto.setter 

111 def model_proto(self, model_proto: onnx.ModelProto): 

112 self.model_proto_ = model_proto 

113 self.graphs_ = list(self.enumerate_graph_protos()) 

114 

115 def enumerate_graph_protos(self) -> Iterable[onnx.GraphProto]: 

116 """Enumerates all GraphProtos in a model.""" 

117 yield self.model_proto.graph 

118 yield from _enumerate_subgraphs(self.model_proto.graph) 

119 

120 def is_in_memory_external_initializer(self, name: str) -> bool: 

121 """Tells if an initializer name is an external initializer stored in memory. 

122 The name must start with '#' in that case. 

123 """ 

124 return name.startswith("#") 

125 

126 def set_large_initializers(self, large_initializers: dict[str, np.ndarray]): 

127 """Adds all large tensors (not stored in the model).""" 

128 for k in large_initializers: 

129 if not self.is_in_memory_external_initializer(k): 

130 raise ValueError( 

131 f"The location {k!r} must start with '#' to be ignored by check model." 

132 ) 

133 self.large_initializers = large_initializers 

134 

135 def check_large_initializers(self) -> None: 

136 for tensor in ext_data._get_all_tensors(self.model_proto): 

137 if not ext_data.uses_external_data(tensor): 

138 continue 

139 prop: onnx.StringStringEntryProto | None = None 

140 for ext in tensor.external_data: 

141 if ext.key == "location": 

142 prop = ext 

143 if prop is None: 

144 raise RuntimeError( 

145 f"No location found for tensor name {tensor.name!r}." 

146 ) 

147 if prop.value not in self.large_initializers: 

148 raise RuntimeError( 

149 f"Unable to find large tensor named {tensor.name!r} " 

150 f"with location {prop.value!r} in " 

151 f"{sorted(self.large_initializers)}." 

152 ) 

153 

154 def _save_external( 

155 self, file_path: str, all_tensors_to_one_file: bool 

156 ) -> onnx.ModelProto: 

157 """Save the large model into a main onnx file and one file 

158 per tensor. Follows the same format as :func:`write_external_data_tensors 

159 <onnx.external_data_helper.write_external_data_tensors>`. 

160 The main model needs to be modified to update the file location, 

161 the function returns this modified copy. 

162 

163 Arguments: 

164 file_path: model file 

165 all_tensors_to_one_file: all tensors in one file 

166 

167 Returns: 

168 modified main model proto 

169 """ 

170 

171 def _clean_name(prefix: str, name: str, unique_names: dict[str, int]) -> str: 

172 if prefix: 

173 name = f"{prefix}-{name}" 

174 for c in ":/\\;,!": 

175 name = name.replace(c, "") 

176 base_name = name 

177 if name in unique_names: 

178 i = unique_names[name] + 1 

179 unique_names[name] = i 

180 return f"{base_name}_{i}" 

181 unique_names[name] = 1 

182 return name 

183 

184 unique_names: dict[str, int] = {} 

185 folder = os.path.dirname(file_path) 

186 if not os.path.exists(folder): 

187 raise FileNotFoundError(f"Folder {folder!r} does not exist.") 

188 proto = self.model_proto.SerializeToString() 

189 copy = onnx.ModelProto() 

190 copy.ParseFromString(proto) 

191 prefix = os.path.splitext(os.path.split(file_path)[-1])[0] 

192 

193 if all_tensors_to_one_file: 

194 file_weight = f"{os.path.split(file_path)[1]}.weight" 

195 full_file_weight = f"{file_path}.weight" 

196 offset = 0 

197 with open(full_file_weight, "wb") as f: 

198 pass 

199 

200 for tensor in ext_data._get_all_tensors(copy): 

201 if not ext_data.uses_external_data(tensor): 

202 continue 

203 prop: onnx.StringStringEntryProto | None = None 

204 for ext in tensor.external_data: 

205 if ext.key == "location": 

206 prop = ext 

207 if prop is None: 

208 raise RuntimeError( 

209 f"No location found for tensor name {tensor.name!r}." 

210 ) 

211 if prop.value not in self.large_initializers: 

212 raise RuntimeError( 

213 f"Unable to find large tensor named {tensor.name!r} " 

214 f"with location {prop.value!r} in " 

215 f"{sorted(self.large_initializers)}." 

216 ) 

217 np_tensor = self.large_initializers[prop.value] 

218 

219 tensor_bytes = onnx.numpy_helper.tobytes_little_endian(np_tensor) 

220 

221 if all_tensors_to_one_file: 

222 _set_external_data( 

223 tensor, 

224 location=file_weight, 

225 offset=offset, 

226 length=len(tensor_bytes), 

227 ) 

228 offset += len(tensor_bytes) 

229 with open(full_file_weight, "ab") as f: 

230 f.write(tensor_bytes) 

231 else: 

232 name = f"{_clean_name(prefix, prop.value, unique_names)}.weight" 

233 _set_external_data(tensor, location=name) 

234 full_name = os.path.join(folder, name) 

235 prop.value = name 

236 with open(full_name, "wb") as f: 

237 f.write(tensor_bytes) 

238 

239 with open(file_path, "wb") as f: 

240 f.write(copy.SerializeToString()) 

241 return copy 

242 

243 def save( 

244 self, 

245 file_path: str, 

246 all_tensors_to_one_file: bool = False, 

247 ) -> onnx.ModelProto: 

248 """Save the large model. 

249 The function returns a ModelProto, 

250 the current one if the model did not need any modification, 

251 a modified copy of it if it required changes such as giving file names 

252 to every external tensor. 

253 

254 Arguments: 

255 file_path: model file 

256 all_tensors_to_one_file: saves all large tensors in one file or 

257 one file per lerge tensor 

258 

259 Returns: 

260 the saved ModelProto 

261 """ 

262 return self._save_external( 

263 file_path, all_tensors_to_one_file=all_tensors_to_one_file 

264 ) 

265 

266 def load(self, file_path: str, load_large_initializers: bool = True): 

267 """Load the large model. 

268 

269 Arguments: 

270 file_path: model file 

271 load_large_initializers: loads the large initializers, 

272 if not done, the model is incomplete but it can be used to 

273 look into the model without executing it and method 

274 :meth:`_load_large_initializers` can be used to load them later 

275 """ 

276 self.model_proto_ = onnx.load_model(file_path, load_external_data=False) 

277 if load_large_initializers: 

278 self._load_large_initializers(file_path) 

279 

280 def _load_large_initializers(self, file_path): 

281 """Loads large initializers. 

282 

283 Arguments: 

284 file_path: model file, the weight are expected to be in the same folder as this file 

285 """ 

286 if self.model_proto_ is None: 

287 raise RuntimeError("A model must be loaded before loading the weights.") 

288 self.large_initializers = {} 

289 base_dir = os.path.dirname(file_path) 

290 for i, tensor in enumerate(ext_data._get_all_tensors(self.model_proto_)): 

291 if not ext_data.uses_external_data(tensor): 

292 continue 

293 

294 info = ext_data.ExternalDataInfo(tensor) 

295 key = f"#t{i}" 

296 _set_external_data(tensor, location=key) 

297 

298 fd = ext_data._open_external_data_fd( 

299 base_dir, info.location, tensor.name, True 

300 ) 

301 with os.fdopen(fd, "rb") as data_file: 

302 raw_data = ext_data._validate_external_data_file_bounds( 

303 data_file, info, tensor.name 

304 ) 

305 

306 dtype = onnx.helper.tensor_dtype_to_np_dtype(tensor.data_type) 

307 shape = tuple(tensor.dims) 

308 

309 if sys.byteorder == "big": 

310 np_tensor = ( 

311 np.frombuffer(raw_data, dtype=dtype).byteswap().reshape(shape) 

312 ) 

313 else: 

314 np_tensor = np.frombuffer(raw_data, dtype=dtype).reshape(shape) 

315 

316 self.large_initializers[key] = np_tensor 

317 

318 

319def make_large_model( 

320 graph: onnx.GraphProto, 

321 large_initializers: dict[str, np.ndarray] | None = None, 

322 **kwargs: Any, 

323) -> ModelContainer: 

324 """Construct a ModelContainer 

325 

326 C API and Python API of protobuf do not operate without serializing 

327 the protos. This function uses the Python API of ModelContainer. 

328 

329 Arguments: 

330 graph: *make_graph* returns 

331 large_initializers: dictionary `name: large tensor`, 

332 large tensor is any python object supporting the DLPack protocol, 

333 the ownership the tensor is transferred to the ModelContainer, 

334 the tensor must define method `tobytes` like numpy tensors 

335 **kwargs: any attribute to add to the returned instance 

336 

337 Returns: 

338 ModelContainer 

339 """ 

340 model = onnx.helper.make_model(graph, **kwargs) 

341 large_model = ModelContainer() 

342 large_model.model_proto = model 

343 if large_initializers: 

344 large_model.set_large_initializers(large_initializers) 

345 large_model.check_large_initializers() 

346 return large_model