Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: size a local model by one copy of its weights (#10558)

Nilay3b33aacf37a8
diff --git a/studio/backend/tests/test_export_size_estimate.py b/studio/backend/tests/test_export_size_estimate.py
index 6976187d831..197fdb22a5f 100644
--- a/studio/backend/tests/test_export_size_estimate.py
+++ b/studio/backend/tests/test_export_size_estimate.py
@@ -3,7 +3,8 @@
"""Tests for GET /api/models/export-size (the Export page size estimate).
-The endpoint must never raise and must degrade to nulls when size is unknown.
+The endpoint must never raise and must degrade to nulls when size is unknown, and the local
+folder sizer behind it must charge one copy of the weights and no trainer bookkeeping.
"""
import asyncio
@@ -14,6 +15,8 @@ import unittest
from pathlib import Path
from unittest.mock import patch
+from utils.hardware.hardware import _get_local_weight_size_bytes
+
_BACKEND_ROOT = Path(__file__).resolve().parent.parent
# Real Qwen3.6-35B-A3B: 35.95B params -> ~67 GiB bf16 (UI wrongly showed Q8 ~8.2 GB).
@@ -229,7 +232,6 @@ class TestExportSizeEndpoint(unittest.TestCase):
def test_local_weight_size_skips_nested_checkpoints(self):
# A run dir's intermediate checkpoint-*/global_step* snapshots must not
# be counted; only the model files at the root are summed.
- from utils.hardware.hardware import _get_local_weight_size_bytes
with tempfile.TemporaryDirectory() as tmp:
run = Path(tmp)
(run / "model.safetensors").write_bytes(b"\0" * 1000)
@@ -240,5 +242,716 @@ class TestExportSizeEndpoint(unittest.TestCase):
self.assertEqual(_get_local_weight_size_bytes(str(run)), 1000)
+def _write(path: Path, size: int) -> None:
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(b"\0" * size)
+
+
+def _write_index(path: Path, shards: dict) -> None:
+ import json
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_text(
+ json.dumps(
+ {
+ "metadata": {"total_size": sum(shards.values())},
+ "weight_map": {f"layer.{i}.weight": name for i, name in enumerate(sorted(shards))},
+ }
+ )
+ )
+
+
+def test_dual_format_repo_counts_safetensors_only(tmp_path):
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "original" / "consolidated.00.pth", 1200)
+ _write(tmp_path / "training_args.bin", 500)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_full_finetune_output_dir_ignores_bookkeeping(tmp_path):
+ _write(tmp_path / "model-00001-of-00002.safetensors", 4000)
+ _write(tmp_path / "model-00002-of-00002.safetensors", 3000)
+ _write(tmp_path / "training_args.bin", 500)
+ _write(tmp_path / "optimizer.pt", 8000)
+ _write(tmp_path / "scheduler.pt", 100)
+ _write(tmp_path / "rng_state.pth", 100)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 7000
+
+
+def test_bin_only_repo_still_sums_shards(tmp_path):
+ _write(tmp_path / "pytorch_model-00001-of-00002.bin", 4000)
+ _write(tmp_path / "pytorch_model-00002-of-00002.bin", 3000)
+ _write(tmp_path / "training_args.bin", 500)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 7000
+
+
+def test_diffusers_subfolder_bin_components_are_counted(tmp_path):
+ _write(tmp_path / "unet" / "diffusion_pytorch_model.bin", 3440)
+ _write(tmp_path / "vae" / "diffusion_pytorch_model.bin", 320)
+ _write(tmp_path / "text_encoder" / "pytorch_model.bin", 460)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 4220
+
+
+def test_mixed_format_components_are_all_counted(tmp_path):
+ _write(tmp_path / "unet" / "diffusion_pytorch_model.safetensors", 9900)
+ _write(tmp_path / "vae" / "diffusion_pytorch_model.bin", 320)
+ _write(tmp_path / "text_encoder_2" / "pytorch_model.bin", 9500)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 19720
+
+
+def test_torch_only_tower_beside_safetensors_language_model(tmp_path):
+ _write(tmp_path / "model-00001-of-00001.safetensors", 13400)
+ _write(tmp_path / "vision_tower" / "pytorch_model.bin", 1700)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 15100
+
+
+def test_independent_torch_payload_in_the_same_directory_is_counted(tmp_path):
+ _write(tmp_path / "model.safetensors", 13400)
+ _write(tmp_path / "mm_projector.bin", 1700)
+ _write(tmp_path / "projector.pt", 300)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 15400
+
+
+def test_freely_named_torch_checkpoints_are_counted(tmp_path):
+ _write(tmp_path / "open_clip" / "open_clip_pytorch_model.bin", 3900)
+ _write(tmp_path / "lora" / "pytorch_lora_weights.bin", 150)
+ _write(tmp_path / "esm" / "esm2_t33_650M_UR50D.pt", 2600)
+ _write(tmp_path / "legacy" / "weights.pth", 1200)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 7850
+
+
+def test_original_copy_counts_when_it_is_the_only_copy(tmp_path):
+ _write(tmp_path / "original" / "consolidated.00.pth", 16000)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 16000
+
+
+def test_root_copy_wins_over_a_larger_original_copy(tmp_path):
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "original" / "consolidated.00.pth", 1100)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_original_only_base_beside_an_external_tower_counts_both(tmp_path):
+ _write(tmp_path / "original" / "consolidated.00.pth", 16000)
+ _write(tmp_path / "vision_tower" / "pytorch_model.bin", 1700)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 17700
+
+
+def test_uppercase_extension_is_not_a_loadable_weight(tmp_path):
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "stale.SAFETENSORS", 5000)
+ _write(tmp_path / "stale.BIN", 5000)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_safetensors_optimizer_sidecar_is_bookkeeping(tmp_path):
+ _write(tmp_path / "model-00001-of-00002.safetensors", 4000)
+ _write(tmp_path / "model-00002-of-00002.safetensors", 3000)
+ _write(tmp_path / "optimizer.safetensors", 8000)
+ _write(tmp_path / "scheduler.safetensors", 100)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 7000
+
+
+def test_sharded_optimizer_state_is_bookkeeping(tmp_path):
+ _write(tmp_path / "model-00001-of-00002.safetensors", 4000)
+ _write(tmp_path / "model-00002-of-00002.safetensors", 3000)
+ _write(tmp_path / "optimizer-00001-of-00002.bin", 8000)
+ _write(tmp_path / "optimizer-00002-of-00002.bin", 8000)
+ _write(tmp_path / "rng_state_0.pth", 100)
+ _write(tmp_path / "rng_state_1.pth", 100)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 7000
+
+
+def test_precision_variant_beside_canonical_weights_charges_one_copy(tmp_path):
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "model.fp16.safetensors", 500)
+ _write(tmp_path / "unet" / "diffusion_pytorch_model.safetensors", 3440)
+ _write(tmp_path / "unet" / "diffusion_pytorch_model.fp16.safetensors", 1720)
+ _write(tmp_path / "unet" / "diffusion_pytorch_model.bin", 3440)
+ _write(tmp_path / "unet" / "diffusion_pytorch_model.fp16.bin", 1720)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 4440
+
+
+def test_sharded_precision_variant_is_held_back_by_the_index(tmp_path):
+ shards = {"model-00001-of-00002.safetensors": 600, "model-00002-of-00002.safetensors": 400}
+ for name, size in shards.items():
+ _write(tmp_path / name, size)
+ _write_index(tmp_path / "model.safetensors.index.json", shards)
+ _write(tmp_path / "model.fp16-00001-of-00002.safetensors", 300)
+ _write(tmp_path / "model.fp16-00002-of-00002.safetensors", 200)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_variant_after_the_shard_counter_is_the_same_archive(tmp_path):
+ shards = {"model-00001-of-00002.safetensors": 600, "model-00002-of-00002.safetensors": 400}
+ for name, size in shards.items():
+ _write(tmp_path / name, size)
+ _write_index(tmp_path / "model.safetensors.index.json", shards)
+ _write(tmp_path / "model-00001-of-00002.fp16.safetensors", 300)
+ _write(tmp_path / "model-00002-of-00002.fp16.safetensors", 200)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_diffusers_sharded_component_is_charged_by_its_index_once(tmp_path):
+ # genmo/mochi-1-preview: sharded denoiser with bf16 twins, components with variants and .bin.
+ shards = {
+ "diffusion_pytorch_model-00001-of-00002.safetensors": 3000,
+ "diffusion_pytorch_model-00002-of-00002.safetensors": 2000,
+ }
+ for name, size in shards.items():
+ _write(tmp_path / "transformer" / name, size)
+ _write_index(
+ tmp_path / "transformer" / "diffusion_pytorch_model.safetensors.index.json", shards
+ )
+ _write(
+ tmp_path / "transformer" / "diffusion_pytorch_model-00001-of-00002.bf16.safetensors", 1500
+ )
+ _write(
+ tmp_path / "transformer" / "diffusion_pytorch_model-00002-of-00002.bf16.safetensors", 1000
+ )
+ _write(tmp_path / "vae" / "diffusion_pytorch_model.safetensors", 320)
+ _write(tmp_path / "vae" / "diffusion_pytorch_model.fp16.safetensors", 160)
+ _write(tmp_path / "vae" / "diffusion_pytorch_model.bin", 320)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 5320
+
+
+def test_an_unrelated_index_json_is_never_opened(tmp_path, monkeypatch):
+ from utils.hardware import hardware
+
+ _write(tmp_path / "model.safetensors", 1000)
+ (tmp_path / "search.index.json").write_text('{"weight_map": {"x": "model.safetensors"}}')
+ opened = []
+ real = hardware._index_targets
+
+ def spy(index, directory):
+ opened.append(index.name)
+ return real(index, directory)
+
+ monkeypatch.setattr(hardware, "_index_targets", spy)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+ assert "search.index.json" not in opened
+
+
+def test_a_variant_only_spelling_is_held_beside_the_loadable_one(tmp_path):
+ _write(tmp_path / "model.fp16.safetensors", 500)
+ _write(tmp_path / "pytorch_model.bin", 1000)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_same_stem_copy_of_the_archive_is_not_a_component(tmp_path):
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "model.pt", 1000)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_diffusers_index_outranks_the_direct_file_beside_it(tmp_path):
+ shards = {
+ "diffusion_pytorch_model-00001-of-00002.safetensors": 3000,
+ "diffusion_pytorch_model-00002-of-00002.safetensors": 2000,
+ }
+ for name, size in shards.items():
+ _write(tmp_path / "unet" / name, size)
+ _write_index(tmp_path / "unet" / "diffusion_pytorch_model.safetensors.index.json", shards)
+ _write(tmp_path / "unet" / "diffusion_pytorch_model.safetensors", 100)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 5000
+
+
+def test_a_transformers_direct_file_still_outranks_a_stale_index(tmp_path):
+ shards = {"model-00001-of-00002.safetensors": 3000, "model-00002-of-00002.safetensors": 2000}
+ for name, size in shards.items():
+ _write(tmp_path / name, size)
+ _write_index(tmp_path / "model.safetensors.index.json", shards)
+ _write(tmp_path / "model.safetensors", 100)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 100
+
+
+def test_every_non_default_variant_is_held_with_its_archive(tmp_path):
+ component = tmp_path / "transformer"
+ _write(component / "diffusion_pytorch_model.safetensors", 4000)
+ _write(component / "diffusion_pytorch_model.fp8.safetensors", 2000)
+ _write(component / "diffusion_pytorch_model.fp8_e4m3fn-00001-of-00002.safetensors", 900)
+ _write(component / "diffusion_pytorch_model.fp8_e4m3fn-00002-of-00002.safetensors", 900)
+ _write(component / "diffusion_pytorch_model.non_ema.safetensors", 4000)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 4000
+
+
+def test_a_declared_diffusers_component_never_opens_a_stray_model_safetensors(tmp_path):
+ (tmp_path / "unet").mkdir()
+ (tmp_path / "unet" / "config.json").write_text('{"_class_name": "UNet2DConditionModel"}')
+ _write(tmp_path / "unet" / "diffusion_pytorch_model.safetensors", 4000)
+ _write(tmp_path / "unet" / "model.safetensors", 35)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 4000
+
+
+def test_a_declared_transformers_component_never_opens_a_stray_diffusion_file(tmp_path):
+ # linyq/kiwi-edit-5b-instruct-only-diffusers/mllm_encoder: a transformers archive with a
+ # 35 MB diffusion_pytorch_model.safetensors beside it.
+ component = tmp_path / "mllm_encoder"
+ component.mkdir()
+ (component / "config.json").write_text('{"architectures": ["Qwen2ForCausalLM"]}')
+ shards = {"model-00001-of-00002.safetensors": 4000, "model-00002-of-00002.safetensors": 3510}
+ for name, size in shards.items():
+ _write(component / name, size)
+ _write_index(component / "model.safetensors.index.json", shards)
+ _write(component / "diffusion_pytorch_model.safetensors", 35)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 7510
+
+
+def test_an_undeclared_folder_holding_both_spellings_charges_both_payloads(tmp_path):
+ _write(tmp_path / "comp" / "diffusion_pytorch_model.safetensors", 4000)
+ _write(tmp_path / "comp" / "model.safetensors", 35)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 4035
+
+
+def test_a_dotdot_in_the_model_path_keeps_the_indexed_shards(tmp_path):
+ model = tmp_path / "existing" / "model"
+ _write(model / "shard.bin", 600)
+ _write(model / "payload", 400)
+ (model / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "shard.bin", "b": "payload"}}'
+ )
+ (tmp_path / "existing" / "other").mkdir()
+ dotted = str(tmp_path / "existing" / "other" / ".." / "model")
+ assert _get_local_weight_size_bytes(dotted) == 1000
+
+
+def test_a_diffusers_pickle_index_is_never_opened(tmp_path):
+ unet = tmp_path / "unet"
+ _write(unet / "diffusion_pytorch_model.bin", 100)
+ _write(unet / "diffusion_pytorch_model-00001-of-00001.bin", 5000)
+ (unet / "diffusion_pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "diffusion_pytorch_model-00001-of-00001.bin"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 100
+
+
+def test_nested_indexed_shards_hold_their_obsolete_sibling(tmp_path):
+ _write(tmp_path / "weights" / "model-00001-of-00002.safetensors", 600)
+ _write(tmp_path / "weights" / "model-00002-of-00002.safetensors", 400)
+ _write(tmp_path / "weights" / "model-00003-of-00002.safetensors", 999)
+ (tmp_path / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "weights/model-00001-of-00002.safetensors",'
+ ' "b": "weights/model-00002-of-00002.safetensors"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_root_bookkeeping_beside_component_archives_is_dropped(tmp_path):
+ _write(tmp_path / "transformer" / "diffusion_pytorch_model.safetensors", 4000)
+ _write(tmp_path / "vae" / "diffusion_pytorch_model.safetensors", 320)
+ _write(tmp_path / "optimizer.pt", 8000)
+ _write(tmp_path / "scheduler.pt", 100)
+ _write(tmp_path / "training_args.bin", 500)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 4320
+
+
+def test_trainer_state_beside_a_freely_named_payload_alone_still_counts(tmp_path):
+ # No loadable archive marks weights.pth the model or optimizer.pt its state, so both count.
+ _write(tmp_path / "weights.pth", 4000)
+ _write(tmp_path / "optimizer.pt", 8000)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 12000
+
+
+def test_variant_only_shards_are_summed(tmp_path):
+ _write(tmp_path / "model-00001-of-00002.fp16.safetensors", 300)
+ _write(tmp_path / "model-00002-of-00002.fp16.safetensors", 200)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 500
+
+
+def test_same_directory_dual_format_charges_the_safetensors_copy(tmp_path):
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "pytorch_model.bin", 1500)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_sharded_dual_format_charges_the_safetensors_copy(tmp_path):
+ _write(tmp_path / "model-00001-of-00002.safetensors", 600)
+ _write(tmp_path / "model-00002-of-00002.safetensors", 400)
+ _write(tmp_path / "pytorch_model-00001-of-00002.bin", 650)
+ _write(tmp_path / "pytorch_model-00002-of-00002.bin", 400)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_consolidated_beside_sharded_safetensors_charges_one_copy(tmp_path):
+ _write(tmp_path / "consolidated.safetensors", 1000)
+ _write(tmp_path / "model-00001-of-00002.safetensors", 600)
+ _write(tmp_path / "model-00002-of-00002.safetensors", 400)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_same_stem_dual_format_charges_one_copy(tmp_path):
+ _write(tmp_path / "v1-5-pruned.safetensors", 4000)
+ _write(tmp_path / "v1-5-pruned.pth", 5000)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 4000
+
+
+def test_adapter_dual_format_charges_one_copy(tmp_path):
+ _write(tmp_path / "adapter_model.safetensors", 300)
+ _write(tmp_path / "adapter_model.bin", 400)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 300
+
+
+def test_an_adapter_is_charged_on_top_of_the_base_model_it_adapts(tmp_path):
+ # peft loads the adapter onto a base already resident, so both are needed.
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "adapter_model.safetensors", 50)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1050
+
+
+def test_an_adapter_never_stands_in_for_bare_shards_beside_it(tmp_path):
+ # Nothing opens the bare shards by name; charging the adapter alone reports 50 bytes for 1000.
+ _write(tmp_path / "model-00001-of-00002.safetensors", 600)
+ _write(tmp_path / "model-00002-of-00002.safetensors", 400)
+ _write(tmp_path / "adapter_model.safetensors", 50)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1050
+
+
+def test_an_unreadable_index_does_not_let_an_adapter_outrank_the_shards(tmp_path):
+ _write(tmp_path / "model-00001-of-00002.safetensors", 600)
+ _write(tmp_path / "model-00002-of-00002.safetensors", 400)
+ (tmp_path / "model.safetensors.index.json").write_text("{ truncated")
+ _write(tmp_path / "adapter_model.bin", 50)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1050
+
+
+def test_an_adapter_beside_legacy_shards_is_charged_with_them(tmp_path):
+ _write(tmp_path / "pytorch_model-00001-of-00002.bin", 600)
+ _write(tmp_path / "pytorch_model-00002-of-00002.bin", 400)
+ _write(tmp_path / "adapter_model.safetensors", 50)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1050
+
+
+def test_index_decides_which_shards_are_loaded(tmp_path):
+ _write(tmp_path / "model-00001-of-00002.safetensors", 600)
+ _write(tmp_path / "model-00002-of-00002.safetensors", 400)
+ _write(tmp_path / "model-00003-of-00002.safetensors", 999)
+ (tmp_path / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "model-00001-of-00002.safetensors",'
+ ' "b": "model-00002-of-00002.safetensors"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_an_unreadable_index_falls_back_to_the_shards_on_disk(tmp_path):
+ _write(tmp_path / "model-00001-of-00002.safetensors", 600)
+ _write(tmp_path / "model-00002-of-00002.safetensors", 400)
+ (tmp_path / "model.safetensors.index.json").write_text("{ not json")
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_bookkeeping_name_counts_where_it_is_the_only_weight(tmp_path):
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "scaler" / "scaler.safetensors", 300)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1300
+
+
+def test_a_bookkeeping_prefix_is_not_a_bookkeeping_name(tmp_path):
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "scheduler_transformer.safetensors", 300)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1300
+
+
+def test_a_direct_safetensors_file_outranks_a_stale_index(tmp_path):
+ _write(tmp_path / "model.safetensors", 100)
+ _write(tmp_path / "model-00001-of-00001.safetensors", 1000)
+ (tmp_path / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "model-00001-of-00001.safetensors"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 100
+
+
+def test_an_index_that_names_the_direct_file_is_not_stale(tmp_path):
+ # unsloth/Qwen3.8-27B-NVFP4 ships model.safetensors beside an 0.85 GB MTP head its index
+ # names too, so reading the direct file as the whole archive would drop the head.
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "model_mtp.safetensors", 50)
+ (tmp_path / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "model.safetensors", "b": "model_mtp.safetensors"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1050
+
+
+def test_a_direct_pickle_file_outranks_its_own_index(tmp_path):
+ _write(tmp_path / "pytorch_model.bin", 100)
+ _write(tmp_path / "pytorch_model-00001-of-00001.bin", 1000)
+ (tmp_path / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "pytorch_model-00001-of-00001.bin"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 100
+
+
+def test_a_loadable_pickle_outranks_safetensors_shards_no_index_names(tmp_path):
+ _write(tmp_path / "pytorch_model.bin", 1000)
+ _write(tmp_path / "model-00001-of-00002.safetensors", 100)
+ _write(tmp_path / "model-00002-of-00002.safetensors", 100)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_pickle_index_is_read_when_no_safetensors_archive_exists(tmp_path):
+ _write(tmp_path / "pytorch_model-00001-of-00002.bin", 600)
+ _write(tmp_path / "pytorch_model-00002-of-00002.bin", 400)
+ _write(tmp_path / "pytorch_model-00003-of-00002.bin", 900)
+ (tmp_path / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "pytorch_model-00001-of-00002.bin",'
+ ' "b": "pytorch_model-00002-of-00002.bin"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_safetensors_index_outranks_a_direct_pickle_file(tmp_path):
+ _write(tmp_path / "model-00001-of-00001.safetensors", 1000)
+ _write(tmp_path / "pytorch_model.bin", 1500)
+ (tmp_path / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "model-00001-of-00001.safetensors"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_an_original_copy_never_outranks_the_weights_the_directory_has(tmp_path):
+ _write(tmp_path / "pytorch_model.bin", 1000)
+ _write(tmp_path / "original" / "model.safetensors", 100)
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_projector_beside_indexed_weights_is_counted(tmp_path):
+ _write(tmp_path / "model-00001-of-00002.safetensors", 600)
+ _write(tmp_path / "model-00002-of-00002.safetensors", 400)
+ _write(tmp_path / "mm_projector.bin", 300)
+ (tmp_path / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "model-00001-of-00002.safetensors",'
+ ' "b": "model-00002-of-00002.safetensors"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1300
+
+
+def test_a_subfolder_only_a_losing_index_names_is_charged_anyway(tmp_path):
+ # Nothing tells this folder from a component that is loaded, and hiding a real one is worse.
+ _write(tmp_path / "sf" / "model-00001-of-00001.safetensors", 1000)
+ _write(tmp_path / "pk" / "pytorch_model-00001-of-00001.bin", 1500)
+ (tmp_path / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "sf/model-00001-of-00001.safetensors"}}'
+ )
+ (tmp_path / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "pk/pytorch_model-00001-of-00001.bin"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 2500
+
+
+def test_an_index_names_a_shard_that_carries_no_weight_extension(tmp_path):
+ _write(tmp_path / "pytorch_model-00001-of-00002.bin", 600)
+ _write(tmp_path / "payload", 400)
+ (tmp_path / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "pytorch_model-00001-of-00002.bin", "b": "payload"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_an_archive_spelled_entirely_without_weight_suffixes_is_read(tmp_path):
+ _write(tmp_path / "payload", 28702)
+ (tmp_path / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "payload", "b": "payload"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 28702
+
+
+def test_an_index_under_original_does_not_charge_the_copy_twice(tmp_path):
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "original" / "consolidated.00.pth", 1200)
+ (tmp_path / "original" / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "consolidated.00.pth"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_vendor_archive_keeps_the_shard_that_could_not_be_folded_up(tmp_path):
+ _write(tmp_path / "original" / "pytorch_model-00001-of-00002.bin", 23143)
+ _write(tmp_path / "original" / "payload", 6079)
+ (tmp_path / "original" / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "pytorch_model-00001-of-00002.bin", "b": "payload"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 29222
+
+
+def test_a_wholly_unsuffixed_vendor_archive_is_read(tmp_path):
+ _write(tmp_path / "original" / "payload", 28702)
+ (tmp_path / "original" / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"w": "payload"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 28702
+
+
+def test_a_vendor_index_does_not_recharge_the_shards_folded_above_it(tmp_path):
+ _write(tmp_path / "model-00001-of-00002.safetensors", 600)
+ _write(tmp_path / "model-00002-of-00002.safetensors", 400)
+ _write(tmp_path / "original" / "consolidated.00.pth", 1100)
+ (tmp_path / "original" / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "consolidated.00.pth"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_stale_vendor_index_does_not_outrank_the_vendor_file_beside_it(tmp_path):
+ _write(tmp_path / "original" / "pytorch_model.bin", 29196)
+ _write(tmp_path / "original" / "payload", 28702)
+ (tmp_path / "original" / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"w": "payload"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 29196
+
+
+def test_a_losing_vendor_archive_contributes_nothing_shard_by_shard(tmp_path):
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "original" / "pytorch_model-00001-of-00002.bin", 23143)
+ _write(tmp_path / "original" / "payload", 6079)
+ (tmp_path / "original" / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "pytorch_model-00001-of-00002.bin", "b": "payload"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_losing_vendor_archive_keeps_an_arbitrary_target_out_too(tmp_path):
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "original" / "payload.bin", 5000)
+ (tmp_path / "original" / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"w": "payload.bin"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_vendor_copy_of_a_nested_component_keeps_its_own_shape(tmp_path):
+ _write(tmp_path / "original" / "vision_tower" / "pytorch_model-00001-of-00002.bin", 23143)
+ _write(tmp_path / "original" / "vision_tower" / "payload", 6079)
+ (tmp_path / "original" / "vision_tower" / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "pytorch_model-00001-of-00002.bin", "b": "payload"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 29222
+
+
+def test_a_nested_vendor_copy_loses_to_the_component_it_copies(tmp_path):
+ _write(tmp_path / "vision_tower" / "model.safetensors", 1000)
+ _write(tmp_path / "original" / "vision_tower" / "payload", 28702)
+ (tmp_path / "original" / "vision_tower" / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"w": "payload"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_vendor_index_of_the_winning_spelling_is_still_the_same_weights(tmp_path):
+ _write(tmp_path / "shard-a.safetensors", 1000)
+ (tmp_path / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "shard-a.safetensors"}}'
+ )
+ _write(tmp_path / "original" / "shard-b.safetensors", 7777)
+ (tmp_path / "original" / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "shard-b.safetensors"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_wholly_unsuffixed_vendor_copy_of_a_nested_component_is_read(tmp_path):
+ _write(tmp_path / "original" / "vision" / "payload", 28702)
+ (tmp_path / "original" / "vision" / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"w": "payload"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 28702
+
+
+def test_a_vendor_index_holds_a_target_named_under_another_extension(tmp_path):
+ _write(tmp_path / "native-shard.safetensors", 1000)
+ (tmp_path / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "native-shard.safetensors"}}'
+ )
+ _write(tmp_path / "original" / "vendor-shard.bin", 5000)
+ (tmp_path / "original" / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "vendor-shard.bin"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_the_directory_a_weight_index_sits_in_is_tried_before_the_vendor_copy(tmp_path):
+ _write(tmp_path / "original" / "native-index-target.safetensors", 1000)
+ _write(tmp_path / "original" / "vendor-target.safetensors", 7777)
+ (tmp_path / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "original/native-index-target.safetensors"}}'
+ )
+ (tmp_path / "original" / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "vendor-target.safetensors"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_weight_index_names_its_shards_in_utf8(tmp_path):
+ # Under the operator's locale the name stops matching; U+00DF cannot normalise away.
+ _write(tmp_path / "model\u00df.safetensors", 1000)
+ _write(tmp_path / "model-00001-of-00001.safetensors", 7777)
+ (tmp_path / "model.safetensors.index.json").write_bytes(
+ b'{"weight_map": {"a": "model\xc3\x9f.safetensors"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_a_subfolder_shard_with_no_weight_suffix_is_still_found(tmp_path):
+ _write(tmp_path / "shards" / "payload", 28702)
+ (tmp_path / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"w": "shards/payload"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 28702
+
+
+def test_a_shard_named_into_a_subfolder_outranks_its_twin_there(tmp_path):
+ _write(tmp_path / "weights" / "shard.bin", 1500)
+ _write(tmp_path / "weights" / "shard.safetensors", 1000)
+ (tmp_path / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "weights/shard.bin"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1500
+
+
+def test_a_deeper_index_cannot_recharge_a_shard_already_claimed_above_it(tmp_path):
+ _write(tmp_path / "weights" / "pytorch_model-00001-of-00001.bin", 1500)
+ (tmp_path / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "weights/pytorch_model-00001-of-00001.bin"}}'
+ )
+ (tmp_path / "weights" / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "pytorch_model-00001-of-00001.bin"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1500
+
+
+def test_a_passed_over_index_does_not_swallow_a_component_it_names(tmp_path):
+ _write(tmp_path / "model.safetensors", 1000)
+ _write(tmp_path / "vision_tower" / "model.safetensors", 700)
+ (tmp_path / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "vision_tower/model.safetensors"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1700
+
+
+def test_an_index_reaching_into_the_vendor_copy_is_still_one_archive(tmp_path):
+ _write(tmp_path / "shard-a.safetensors", 600)
+ _write(tmp_path / "original" / "shard-b.safetensors", 400)
+ (tmp_path / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"a": "shard-a.safetensors", "b": "original/shard-b.safetensors"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1000
+
+
+def test_an_index_target_that_walks_back_up_lands_where_the_loader_lands(tmp_path):
+ _write(tmp_path / "weights" / "shard.bin", 1500)
+ _write(tmp_path / "weights" / "shard.safetensors", 1000)
+ (tmp_path / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "weights/../weights/shard.bin"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 1500
+
+
+def test_a_subfolder_component_the_index_ignores_is_still_counted(tmp_path):
+ _write(tmp_path / "weights" / "shard.bin", 1500)
+ _write(tmp_path / "vision_tower" / "model.safetensors", 700)
+ (tmp_path / "pytorch_model.bin.index.json").write_text(
+ '{"weight_map": {"a": "weights/shard.bin"}}'
+ )
+ assert _get_local_weight_size_bytes(str(tmp_path)) == 2200
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 94343d5529a..e45e9552f44 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -5689,24 +5689,330 @@ def _resolve_model_identifier_for_gpu_estimate(
return model_name
+_WEIGHT_EXTS = (".safetensors", ".bin", ".pt", ".pth")
+# Shard or copy counter closing a weight stem: model-00001-of-00004, consolidated.00.
+_WEIGHT_COUNTER = re.compile(r"(?:-\d+-of-\d+|\.\d+)$")
+_TRAINER_BOOKKEEPING = re.compile(
+ r"^(?:optimizer|scheduler|scaler|rng_state|training_args|trainer_state)"
+ r"(?:[-_]\d+(?:-of-\d+)?)?$"
+)
+# A variant (model.fp16.safetensors, model-00001-of-00002.fp8.safetensors) is these weights
+# again and a load passing no variant never opens it; a numeric tail is a shard counter.
+_WEIGHT_VARIANT = re.compile(r"\.([A-Za-z][\w-]*)$")
+# The order from_pretrained tries, the direct file ahead of the index within each spelling.
+_TRANSFORMERS_ARCHIVES = (
+ ("model", ".safetensors"),
+ ("pytorch_model", ".bin"),
+ ("consolidated", ".safetensors"),
+ ("consolidated", ".pth"),
+)
+# diffusers resolves one name per component, its index or the direct file, safetensors first.
+# Which table a folder loads by is its declared class, not a fixed order.
+_DIFFUSERS_ARCHIVES = (
+ ("diffusion_pytorch_model", ".safetensors"),
+ ("diffusion_pytorch_model", ".bin"),
+)
+_MODEL_ARCHIVES = _TRANSFORMERS_ARCHIVES + _DIFFUSERS_ARCHIVES
+# peft's own table: an adapter loads on top of the base model, so it never stands in for one.
+_ADAPTER_ARCHIVES = (
+ ("adapter_model", ".safetensors"),
+ ("adapter_model", ".bin"),
+)
+_WEIGHT_ARCHIVES = _MODEL_ARCHIVES + _ADAPTER_ARCHIVES
+# The only indexes a load resolves; any other *.index.json in the folder is never opened.
+_WEIGHT_INDEX_NAMES = frozenset(f"{base}{ext}.index.json" for base, ext in _WEIGHT_ARCHIVES)
+
+
+def _archive_stem(stem: str) -> tuple:
+ """``(base, variant)`` of a weight stem, the shard counter and the precision variant
+ stripped in either order: model-00001-of-00002.fp16 and model.fp16-00001-of-00002 are
+ both ``("model", "fp16")``; consolidated.00 is ``("consolidated", None)``."""
+ stem = _WEIGHT_COUNTER.sub("", stem)
+ variant = _WEIGHT_VARIANT.search(stem)
+ if variant is None:
+ return stem, None
+ return _WEIGHT_COUNTER.sub("", stem[: variant.start()]), variant.group(1)
+
+
+def _declared_library(directories: list) -> Optional[str]:
+ """Which loader a folder's own config.json says opens it: a diffusers component carries
+ ``_class_name``/``_diffusers_version``, a transformers model ``architectures``/``model_type``.
+ ``None`` when the folder declares nothing, and its spellings are then two payloads."""
+ for directory in directories:
+ try:
+ config = json.loads((directory / "config.json").read_text(encoding = "utf-8"))
+ except (OSError, ValueError):
+ continue
+ if not isinstance(config, dict):
+ continue
+ if "_class_name" in config or "_diffusers_version" in config:
+ return "diffusers"
+ if "architectures" in config or "model_type" in config:
+ return "transformers"
+ return None
+
+
+def _index_targets(index: Path, directory: Path) -> set:
+ """What an index names, joined onto its folder the way from_pretrained joins it."""
+ try:
+ weight_map = json.loads(index.read_text(encoding = "utf-8")).get("weight_map") or {}
+ return {Path(os.path.normpath(directory / name)) for name in weight_map.values()}
+ except (OSError, ValueError, AttributeError, TypeError):
+ return set()
+
+
+def _indexed_archive(directories: list, base: str, ext: str, tree: dict) -> tuple:
+ """The shards from_pretrained opens here, and every shard any of these indexes names."""
+ files, settled, read = tree["files"], tree["settled"], tree["read"]
+ chosen: dict = {}
+ every: dict = {}
+ for directory in directories:
+ index = directory / f"{base}{ext}.index.json"
+ if index not in read:
+ read[index] = _index_targets(index, directory)
+ shards = {
+ path: files[path]
+ for path in read[index]
+ if path in files and (path.parent, path.stem) not in settled
+ }
+ every.update(shards)
+ if shards and not chosen:
+ chosen = shards
+ return chosen, every
+
+
+def _archive_candidates(directories: list, pool: dict, tree: dict, table: tuple) -> tuple:
+ """Every spelling of the weights present here, in the order from_pretrained tries them,
+ and every file those spellings account for, a variant-only spelling included."""
+ candidates = []
+ held: dict = {}
+ for base, ext in table:
+ direct = {path: size for path, size in pool.items() if path.name == f"{base}{ext}"}
+ indexed, all_indexed = _indexed_archive(directories, base, ext, tree)
+ if base == "diffusion_pytorch_model" and ext == ".bin":
+ # A default diffusers load resolves the safetensors index only; its pickle fallback
+ # asks for the unsharded .bin, so the default path never reaches a .bin.index.json.
+ indexed = {}
+ # No index names these, but a pruned or unwritten index is still that model.
+ counted: dict = {}
+ variants: dict = {}
+ for path, size in pool.items():
+ if path.suffix != ext:
+ continue
+ stem, variant = _archive_stem(path.stem)
+ if stem == base:
+ (variants if variant else counted)[path] = size
+ # A stale index names other files, so the direct one is opened instead. An index naming
+ # the direct file is not stale: it says that file is one part of the archive, so it
+ # decides, and Qwen's NVFP4 MTP head beside model.safetensors is charged with it.
+ names_the_direct_file = bool(direct) and set(direct) <= set(indexed)
+ # diffusers is the other way round: its index settles a component whenever one exists.
+ index_first = names_the_direct_file or (base, ext) == (
+ "diffusion_pytorch_model",
+ ".safetensors",
+ )
+ opens = indexed if (indexed and index_first) else (direct or indexed)
+ # The rest of a spelling is these weights again; a variant-only one is never opened.
+ held.update({**direct, **all_indexed, **counted, **variants})
+ if opens or counted:
+ candidates.append((opens or counted, bool(opens)))
+ return candidates, held
+
+
+def _selected_archive(homes: list, sizes: dict, tree: dict, vendor: set, table: tuple) -> tuple:
+ """The one archive from ``table`` these folders open, and every spelling of it."""
+ directories = [folder for folder, _ in homes]
+ candidates, held = _archive_candidates(directories, sizes, tree, table)
+ # A vendor copy never outranks weights a directory has of its own, and its folder drops out
+ # whole: an index is one archive, so half of one must not outrank a complete candidate.
+ native_pool = {path: size for path, size in sizes.items() if path not in vendor}
+ native, _ = _archive_candidates(
+ [f for f, is_vendor in homes if not is_vendor], native_pool, tree, table
+ )
+
+ archive: dict = {}
+ for choices in (native, candidates):
+ if choices:
+ opens = [entry for entry in choices if entry[1]]
+ archive = (opens or choices)[0][0]
+ break
+
+ # Nothing selected, nothing held: a folder of variant shards alone still counts as weights.
+ return archive, (set(held) if archive else set())
+
+
+def _directory_weight_bytes(homes: list, sizes: dict, tree: dict, vendor: set) -> tuple:
+ """What one directory costs, and every file its spellings account for.
+
+ ``homes`` are the ``(folder, is_vendor)`` pairs answering to it, decided together because
+ splitting them lets a single archive lose in halves. ``tree`` carries every file, since an
+ index may name a shard below itself; the second return is what it accounted for.
+ """
+ # Tables resolved apart: an 80 MB adapter must never stand in for the 8 GB model it adapts.
+ # The transformers and diffusers spellings are two payloads too, unless the folder declares
+ # which class loads it: the other spelling is then one this load never opens, held not charged.
+ transformers_model, transformers_held = _selected_archive(
+ homes, sizes, tree, vendor, _TRANSFORMERS_ARCHIVES
+ )
+ diffusers_model, diffusers_held = _selected_archive(
+ homes, sizes, tree, vendor, _DIFFUSERS_ARCHIVES
+ )
+ library = _declared_library([folder for folder, _ in homes])
+ if library == "diffusers" and diffusers_model:
+ model = diffusers_model
+ elif library == "transformers" and transformers_model:
+ model = transformers_model
+ else:
+ model = {**transformers_model, **diffusers_model}
+ model_held = transformers_held | diffusers_held
+ adapter, adapter_held = _selected_archive(homes, sizes, tree, vendor, _ADAPTER_ARCHIVES)
+ archive = {**model, **adapter}
+
+ # model.pt beside model.safetensors is that archive serialized again, not a second payload.
+ alternatives = model_held | adapter_held
+ archive_stems = {(path.parent, path.stem) for path in archive}
+ alternatives |= {path for path in sizes if (path.parent, path.stem) in archive_stems}
+ rest = {path: size for path, size in sizes.items() if path not in alternatives}
+ here = {folder for folder, _ in homes}
+ above_an_archive = any(
+ folder != other and other.is_relative_to(folder)
+ for folder in here
+ for other in tree.get("archive_dirs", ())
+ )
+ if archive or above_an_archive:
+ rest = {p: s for p, s in rest.items() if not _TRAINER_BOOKKEEPING.match(p.stem)}
+ components: dict = {}
+ ordered = sorted(rest.items(), key = lambda i: (i[0].suffix != ".safetensors", i[0].name))
+ for path, size in ordered:
+ components.setdefault(path.stem, size)
+ accounted = {path for path in alternatives if path.parent in here} | set(archive)
+ # An index reaching into a subfolder claims that shard family whole: a sibling it no longer
+ # names (model-00003-of-00002) is an obsolete shard, not a component.
+ for shard in [path for path in archive if path.parent not in here]:
+ base, _ = _archive_stem(shard.stem)
+ accounted |= {
+ path
+ for path in tree["files"]
+ if path.parent == shard.parent
+ and path.suffix == shard.suffix
+ and _archive_stem(path.stem)[0] == base
+ }
+ return sum(archive.values()) + sum(components.values()), accounted
+
+
def _get_local_weight_size_bytes(model_name: str) -> Optional[int]:
- model_path = Path(model_name)
+ # Lexical, so a `..` cannot make a shard the index names look like it sits outside the model.
+ model_path = Path(os.path.normpath(model_name))
if not model_path.exists():
return None
- weight_exts = (".safetensors", ".bin", ".pt", ".pth")
# Skip intermediate training checkpoints: a run dir can hold several
# checkpoint-*/global_step* snapshots, but export loads only the model at
# the root, so counting them would multiply the estimate.
skip_prefixes = ("checkpoint-", "global_step")
- total = 0
+ found = []
+ indexed_dirs = []
+ index_files = []
+ weight_sizes: dict = {}
+ homes_by_directory: dict = {}
+ vendor: set = set()
+ # Where a folder sits is settled once per folder rather than once per file: a model
+ # directory holds a handful of folders and, beside datasets or logs, a great many files.
+ placed: dict = {}
for file in model_path.rglob("*"):
- if not file.is_file() or file.suffix not in weight_exts:
+ if not file.is_file():
continue
- rel = file.relative_to(model_path)
- if any(part.startswith(skip_prefixes) for part in rel.parts):
+ parent = file.parent
+ if parent not in placed:
+ rel_parent = parent.relative_to(model_path)
+ # A top-level original/ answers to the directory above it, files and index alike; its
+ # real location is kept too, since a nested component's vendor copy keeps its shape.
+ is_vendor = rel_parent.parts[:1] == ("original",)
+ placed[parent] = (
+ any(part.startswith(skip_prefixes) for part in rel_parent.parts),
+ is_vendor,
+ Path(*rel_parent.parts[1:]) if is_vendor else rel_parent,
+ rel_parent,
+ )
+ skipped, is_vendor, home, rel_parent = placed[parent]
+ if skipped or file.name.startswith(skip_prefixes):
continue
- total += file.stat().st_size
+ if is_vendor:
+ vendor.add(file)
+ homes_by_directory.setdefault(home, {})[parent] = is_vendor
+ if file.suffix in _WEIGHT_EXTS:
+ try:
+ weight_sizes[file] = file.stat().st_size
+ except OSError:
+ continue
+ found.append(rel_parent / file.name)
+ elif file.name in _WEIGHT_INDEX_NAMES:
+ index_files.append(file)
+ indexed_dirs.append(home)
+
+ # A vendor copy of a file the directory above already has is those weights renamed.
+ sizes_by_directory: dict = {}
+ names_by_directory: dict = {}
+ for rel in sorted(found, key = lambda r: r.parts[:1] == ("original",)):
+ directory = Path(*rel.parent.parts[1:]) if rel.parts[:1] == ("original",) else rel.parent
+ names = names_by_directory.setdefault(directory, set())
+ if rel.name in names:
+ continue
+ names.add(rel.name)
+ sizes_by_directory.setdefault(directory, {})[model_path / rel] = weight_sizes[
+ model_path / rel
+ ]
+
+ # An index may name shards that carry no recognised suffix, so its directory is read too.
+ for directory in indexed_dirs:
+ sizes_by_directory.setdefault(directory, {})
+
+ # A shallower index can name a shard inside a deeper folder, so it decides first, and by
+ # stem: the twin of a claimed shard is that weight saved twice, not a second component.
+ # Only the weights and index-named paths are stat()ed, so a model kept beside a dataset
+ # costs one stat per weight. The indexes are read once here and handed on.
+ files = dict(weight_sizes)
+ read: dict = {}
+ for index in index_files:
+ read[index] = _index_targets(index, index.parent)
+ for target in read[index]:
+ if target in files:
+ continue
+ try:
+ relative = target.relative_to(model_path)
+ if not target.is_file():
+ continue
+ files[target] = target.stat().st_size
+ except (OSError, ValueError):
+ continue
+ if any(part.startswith(skip_prefixes) for part in relative.parts):
+ del files[target]
+ elif relative.parts[:1] == ("original",):
+ vendor.add(target)
+
+ settled: set = set()
+ # The folders holding a loadable archive: trainer state saved above them, at the root of a
+ # pipeline whose weights live in component folders, is bookkeeping all the same.
+ archive_bases = {base for base, _ in _WEIGHT_ARCHIVES}
+ archive_dirs = {index.parent for index in index_files} | {
+ path.parent for path in weight_sizes if _archive_stem(path.stem)[0] in archive_bases
+ }
+ tree = {"files": files, "settled": settled, "read": read, "archive_dirs": archive_dirs}
+ total = 0
+ for directory in sorted(sizes_by_directory, key = lambda d: (len(d.parts), d.as_posix())):
+ unclaimed = {
+ path: size
+ for path, size in sizes_by_directory[directory].items()
+ if (path.parent, path.stem) not in settled
+ }
+ charged, accounted = _directory_weight_bytes(
+ sorted(homes_by_directory.get(directory, {model_path / directory: False}).items()),
+ unclaimed,
+ tree,
+ vendor,
+ )
+ settled |= {(path.parent, path.stem) for path in accounted}
+ total += charged
return total if total > 0 else None