Tensorizer is a Python library developed by CoreWeave for fast serialization and deserialization of PyTorch modules, models, and tensors. It aims to reduce model load times and CPU memory usage by efficiently streaming tensor data, supporting local filesystems, HTTP/HTTPS, and S3 endpoints. The current version is 2.12.0, with ongoing development and updates primarily driven by CoreWeave's needs for serving large AI models.
pip install tensorizerVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to serialize and deserialize a PyTorch model's state dictionary using `TensorSerializer` and `TensorDeserializer`. It creates a simple neural network, saves its state, loads it into a new instance, and verifies that the outputs match. The `TensorDeserializer` is used as a context manager for proper resource handling.
For models with non-tensor attributes, you must manually serialize and deserialize these components separately or use `tensorizer.torch_compat` which can save arbitrary objects (via pickle) alongside tensors. Be mindful of the security implications of pickling untrusted data.
Only load models from trusted sources when using `tensorizer.torch_compat` or `torch.load`. For maximum security, use `TensorSerializer` and `TensorDeserializer` directly for tensors and manage non-tensor data serialization with a safer format (e.g., JSON, YAML, Protocol Buffers).
Install `libsodium` on your operating system. For Ubuntu/Debian, use `sudo apt-get install libsodium23`. Refer to `libsodium`'s official documentation for other platforms.
Always use `TensorDeserializer` within a `with` statement: `with TensorDeserializer(...) as state_dict: ...`
Monitor CPU and VRAM usage during serialization/deserialization. Scale your compute resources (CPU RAM, GPU VRAM) or consider using smaller models if resource constraints are an issue.
Modify your serialization logic to separately save and load non-tensor attributes using standard Python serialization (e.g., `json`, `pickle` if secure, or other custom methods). Ensure your model re-initialization logic correctly reconstructs these attributes, or use `tensorizer.torch_compat` with awareness of its `pickle` usage.
Install the `libsodium` development package on your system. For Debian/Ubuntu, use `sudo apt-get install libsodium-dev` or `libsodium23`. For other operating systems, consult the `libsodium` official documentation for installation instructions.
Ensure `TensorDeserializer` is used as a context manager when loading state dictionaries or accessing its contents that behave like a dictionary: `with TensorDeserializer(uri) as state_dict: model.load_state_dict(state_dict)`.