重みを標準の safetensors ファイルに書き出す

Jabara のアーカイブにある重みは、チェックポイント全体を復元しなくても、どのツールでも読める safetensors ファイルに書き出せる。jabara export-weights ARCHIVE OUT と jabara.files.export_weights(archive_path, out) は、役割が weight のテンソルを書き出す。コマンドは、OUT がすでにあると書き出さず、jabara: OUT: already exists を出力して終了ステータス 1 で終了する。export_weights は、既存の out ファイルをエラーなしで置き換える。

始める前に

空のディレクトリで始める。make_checkpoint.py をそこに保存して実行する。チュートリアル: チェックポイントを圧縮して復元する と同じく、torch extra と safetensors が必要である。このスクリプトは、例で使う checkpoint-1000/ を書き出す。

$ python make_checkpoint.py

safetensors ファイルのアーカイブを書き出す

*.safetensors ファイルから作ったアーカイブでは、すべてのテンソルの役割が weight で、アーカイブは元のファイルのヘッダも保持している。そのため、出力は元のファイルとバイト単位で同一になる。アーカイブはそのまま残る。checkpoint-1000/model.safetensors.jbr がすでにあるなら、最初のコマンドは実行しない。jabara compress は、ファイルとそのアーカイブが両方あるディレクトリでは圧縮しないからである。

$ jabara compress checkpoint-1000/model.safetensors --keep
checkpoint-1000/model.safetensors.jbr: ... -> ... bytes (...% of original)
$ jabara export-weights checkpoint-1000/model.safetensors.jbr exported.safetensors

export-weights は何も出力しない。Hugging Face の Trainer アダプタが書き出す model.safetensors.jbr にこのコマンドを使えば、チェックポイントを圧縮したままモデルを共有できる。

Python でも同じ処理を行い、書き出したファイルが元のファイルと同一であることを確かめる。

import filecmp

from jabara.files import compress_file, export_weights

compress_file("checkpoint-1000/model.safetensors", keep=True)
export_weights("checkpoint-1000/model.safetensors.jbr", "exported.safetensors")
print(filecmp.cmp("checkpoint-1000/model.safetensors", "exported.safetensors", shallow=False))
True

同じ out で二回目を呼び出すと、ファイルは置き換えられる。

from pathlib import Path

Path("exported.safetensors").write_bytes(b"not a safetensors file")
export_weights("checkpoint-1000/model.safetensors.jbr", "exported.safetensors")
print(filecmp.cmp("checkpoint-1000/model.safetensors", "exported.safetensors", shallow=False))
True

save_state から書き出す

それ以外のアーカイブでは、出力には役割が weight のテンソルだけが、アーカイブでの名前と順序のまま入る。すべてのテンソルの役割を weight にするには、モデルの state_dict を WeightsSchema で保存する(素の PyTorch のループで状態を保存して読み込む を参照)。

import torch
from safetensors.torch import load_file

from jabara.schemas import WeightsSchema
from jabara.torch import save_state

model = torch.nn.Linear(4, 2)
save_state(model.state_dict(), "model.jbr", schema=WeightsSchema())
export_weights("model.jbr", "linear.safetensors")

exported = load_file("linear.safetensors")
print(sorted(exported))
print(all(torch.equal(exported[name], tensor) for name, tensor in model.state_dict().items()))
['bias', 'weight']
True

ヘッダは、8 バイトの倍数になるまで空白で埋められる。safetensors が保持できない dtype では、UnsupportedDtypeError が発生する。

書き出すものがないとき

weight のテンソルがないアーカイブでは ArchiveFormatError が発生し、コマンドは jabara: <archive>: no tensors with role 'weight' を出力して終了ステータス 1 で終了する。既定では、次の二種類のアーカイブに weight のテンソルがない。

  • optimizer.pt のアーカイブ。テンソルはオプティマイザ状態である。

  • jabara compress が .pt ファイルまたは .pth ファイルから作るアーカイブ。compress はこれらのファイルにオプティマイザの役割を割り当てるので、モデルの state_dict のテンソルには役割 other が付く。

.pt ファイルは、読み込んでから、上と同じように WeightsSchema を指定して save_state で保存する。export-weights はベースを受け取らないので、差分アーカイブは読めない(ベースとの差分としてチェックポイントを保存する を参照)。