Implementation:AUTOMATIC1111 Stable diffusion webui Embedding save
| Knowledge Sources | |
|---|---|
| Domains | Serialization, Embedding, Steganography, Textual Inversion |
| Last Updated | 2026-02-08 00:00 GMT |
Overview
Concrete tools for saving trained textual inversion embeddings to .pt files and encoding embedding data as base64 for storage in PNG image metadata, provided by the AUTOMATIC1111 stable-diffusion-webui repository.
Description
The embedding serialization system consists of two key components:
Embedding.save(filename) serializes the embedding to a .pt file using torch.save(). The saved dictionary includes the token-to-parameter mapping (string_to_param), token-to-id mapping (string_to_token), embedding name, training step, and source checkpoint metadata. If shared.opts.save_optimizer_state is enabled and an optimizer state is attached, it is saved to a companion {filename}.optim file alongside a checksum for integrity verification.
embedding_to_b64(data) converts an embedding data dictionary (including torch tensors) to a base64-encoded byte string. It uses a custom EmbeddingEncoder that serializes torch.Tensor objects by converting them to CPU numpy arrays and then to nested Python lists under a TORCHTENSOR key. The result can be stored in PNG tEXt metadata under the sd-ti-embedding key.
The corresponding embedding_from_b64(data) function decodes the base64 string back to a dictionary using a custom EmbeddingDecoder that reconstructs tensors from the TORCHTENSOR lists.
Usage
Use these functions when:
- Saving a trained embedding to disk for deployment or sharing
- Encoding an embedding for storage inside a PNG preview image
- Resuming training and needing to save/restore optimizer state alongside the embedding
- Distributing embeddings as self-contained image files
Code Reference
Source Location
- Repository: stable-diffusion-webui
- File:
modules/textual_inversion/textual_inversion.py(Embedding.save at L54-71) - File:
modules/textual_inversion/image_embedding.py(embedding_to_b64 at L32-34, EmbeddingEncoder at L15-19)
Signature
class Embedding:
def save(self, filename):
"""
Save embedding data to a .pt file.
Optionally saves optimizer state to {filename}.optim if enabled.
Args:
filename (str): Path to save the embedding file.
"""
...
def embedding_to_b64(data):
"""
Encode an embedding data dictionary to base64 bytes.
Args:
data (dict): Embedding dictionary containing torch tensors.
Returns:
bytes: Base64-encoded JSON string.
"""
...
def embedding_from_b64(data):
"""
Decode a base64-encoded embedding back to a dictionary with torch tensors.
Args:
data (str or bytes): Base64-encoded embedding data.
Returns:
dict: Embedding dictionary with reconstructed torch tensors.
"""
...
Import
from modules.textual_inversion.textual_inversion import Embedding
from modules.textual_inversion.image_embedding import embedding_to_b64, embedding_from_b64
I/O Contract
Inputs
Embedding.save:
| Name | Type | Required | Description |
|---|---|---|---|
| filename | str | Yes | Absolute path to the output .pt file. Optimizer state (if enabled) is saved to {filename}.optim
|
embedding_to_b64:
| Name | Type | Required | Description |
|---|---|---|---|
| data | dict | Yes | Embedding data dictionary, typically containing string_to_token, string_to_param (with torch.Tensor values), name, step, sd_checkpoint, and sd_checkpoint_name
|
Outputs
Embedding.save:
| Name | Type | Description |
|---|---|---|
| (none) | None | Writes the .pt file (and optionally .optim file) to disk as a side effect
|
embedding_to_b64:
| Name | Type | Description |
|---|---|---|
| result | bytes | Base64-encoded JSON representation of the embedding data, suitable for storage in PNG tEXt metadata |
Usage Examples
Basic Save
import torch
from modules.textual_inversion.textual_inversion import Embedding
# Create and save an embedding
vec = torch.randn(4, 768)
emb = Embedding(vec, name="my-concept", step=1000)
emb.sd_checkpoint = "abc123def456"
emb.sd_checkpoint_name = "v1-5-pruned-emaonly"
emb.save("/path/to/embeddings/my-concept.pt")
# Creates: /path/to/embeddings/my-concept.pt
# If save_optimizer_state is enabled, also creates: /path/to/embeddings/my-concept.pt.optim
Encoding for PNG Metadata
import torch
from PIL import Image, PngImagePlugin
from modules.textual_inversion.image_embedding import embedding_to_b64
# Load the saved embedding data
data = torch.load("/path/to/embeddings/my-concept.pt")
# Encode to base64 and store in a PNG image
info = PngImagePlugin.PngInfo()
info.add_text("sd-ti-embedding", embedding_to_b64(data))
preview_image = Image.open("/path/to/preview.png")
preview_image.save("/path/to/my-concept.png", "PNG", pnginfo=info)
Round-Trip Encode/Decode
from modules.textual_inversion.image_embedding import embedding_to_b64, embedding_from_b64
import torch
data = {
"string_to_token": {"*": 265},
"string_to_param": {"*": torch.randn(4, 768)},
"name": "test",
"step": 500
}
# Encode
b64_data = embedding_to_b64(data)
# Decode
restored = embedding_from_b64(b64_data)
# Verify
assert restored["name"] == data["name"]
assert restored["step"] == data["step"]
assert torch.allclose(restored["string_to_param"]["*"], data["string_to_param"]["*"], atol=1e-6)