| 190 | |
| 191 | |
| 192 | class ContentStoreReader: |
| 193 | def __init__(self, loc: str, *, cache=True) -> None: |
| 194 | self.loc = loc |
| 195 | self.storage_cache: Optional[ |
| 196 | Dict[Optional[torch.device], Dict[str, StorageWeakRef]] |
| 197 | ] = None |
| 198 | if cache: |
| 199 | self.storage_cache = defaultdict(dict) |
| 200 | |
| 201 | def read_storage(self, h: str, *, device=None) -> torch.UntypedStorage: |
| 202 | if device is not None: |
| 203 | device = torch.device(device) |
| 204 | ws = ( |
| 205 | self.storage_cache[device].get(h) |
| 206 | if self.storage_cache is not None |
| 207 | else None |
| 208 | ) |
| 209 | s: Optional[torch.UntypedStorage] |
| 210 | if ws is not None: |
| 211 | s = torch.UntypedStorage._new_with_weak_ptr(ws.cdata) |
| 212 | if s is not None: |
| 213 | return s |
| 214 | s = torch.load( |
| 215 | os.path.join(self.loc, "storages", h), |
| 216 | weights_only=True, |
| 217 | map_location=device, |
| 218 | )._untyped_storage |
| 219 | assert s is not None |
| 220 | if self.storage_cache is not None: |
| 221 | self.storage_cache[device][h] = StorageWeakRef(s) |
| 222 | return s |
| 223 | |
| 224 | def read_tensor_metadata(self, name: str): |
| 225 | fn = os.path.join(self.loc, "tensors", name) |
| 226 | if not os.path.exists(fn): |
| 227 | raise FileNotFoundError(fn) |
| 228 | return torch.load(fn, weights_only=True) |
| 229 | |
| 230 | def read_tensor(self, name: str, *, device=None) -> torch.Tensor: |
| 231 | dtype, h, storage_offset, size, stride, metadata = self.read_tensor_metadata( |
| 232 | name |
| 233 | ) |
| 234 | storage = self.read_storage(h, device=device) |
| 235 | t = torch.tensor([], dtype=dtype, device=storage.device) |
| 236 | t.set_(storage, storage_offset, size, stride) |
| 237 | torch._utils.set_tensor_metadata(t, metadata) |
| 238 | return t |
no outgoing calls
searching dependent graphs…