Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
Load the VAEs one tensor at a time and recover from WDDM non-local exhaustion (#18)
Bowen Xuec8917f41ee92
diff --git a/freevideo_engine/adaptive.py b/freevideo_engine/adaptive.pyindex e1c55f8..7d2966c 100644--- a/freevideo_engine/adaptive.py+++ b/freevideo_engine/adaptive.py@@ -255,6 +255,23 @@ def reduced_pinning(profile, failure, phase, previous_ram_retries):'Retain host caches with a smaller pin budget; a second RAM failure uses the bounded streaming fallback.')+def nonlocal_exhausted(failure):+ """A CUDA out-of-memory raised while the WDDM non-local budget, not VRAM, was full.++ Page-locked host memory counts against that budget. A 20 s request failed+ with non-local usage at 13.14 of 13.24 GiB, 10.68 GiB of VRAM free and no+ caching-allocator OOM; the failed allocation itself is not in the usage.+ """+ gpu = failure.get('gpu') if isinstance(failure.get('gpu'), dict) else {}+ values = [gpu.get(key) for key in ('nonlocal_budget_bytes', 'nonlocal_usage_bytes',+ 'local_budget_bytes', 'local_usage_bytes')]+ if not all(type(value) is int and value >= 0 for value in values) or not values[0]:+ return False+ budget, usage, local_budget, local_usage = values+ return (usage >= budget - 2**30 and local_usage <= local_budget - 2 * 2**30+ and not gpu.get('allocator_ooms'))++def next_placement(profile, failure, phase, canvas=None, *, previous_ram_retries=0, previous_gpu_retries=0,sampling_complete=False):"""A bounded neutral fallback; never change request, backend or chunking.@@ -279,13 +296,23 @@ def next_placement(profile, failure, phase, canvas=None, *, previous_ram_retriesif options.get(name) != new:changes[section+'.'+name] = {'from': options.get(name), 'to': new}options[name] = new+ host_pins = failure['kind'] == 'gpu_oom' and nonlocal_exhausted(failure)if failure['kind'] == 'gpu_oom':- if recompute_recovery:+ if host_pins and phase in ('load', 'sample') and (engine.get('pin_host_gb', 0.) > 0 or engine.get('pin_host_weights')):+ # Page-locked memory ran out, not VRAM: return pinned weights and+ # keep every GPU setting. Halve once, then pin nothing.+ change('engine', 'pin_host_gb', 0. if previous_gpu_retries else round(engine.get('pin_host_gb', 0.) / 2, 3))+ for name in ('pin_host_weights', 'preload_host'):+ if engine.get(name):+ change('engine', name, False)+ elif recompute_recovery:# Keep the up/down GEMM row shapes, FP8 global scale and requested# output. Only regenerate identical FF tiles instead of stashing# the full intermediate matrix which actually failed to allocate.change('engine', 'fp8_ff_recompute', True)elif phase == 'decode' or resume_finalization:+ if host_pins:+ change('decoder', 'pin_weights', False)change('decoder', 'offload', True)change('decoder', 'prefetch', False)change('decoder', 'stream_output', True)@@ -382,8 +409,9 @@ def next_placement(profile, failure, phase, canvas=None, *, previous_ram_retries'chunk changes require local complete-request equivalence.', 'changes': {}}if 'policy' in value:value['policy'].update(engine=dict(engine), decoder=dict(decoder))+ cause = 'page-locked memory exhausted the WDDM non-local budget' if host_pins else failure['kind']return value, dict(reason='Fresh worker after %s; preserve geometry, steps, seed, precision, '- 'attention and chunk arithmetic.' % failure['kind'], changes=changes,+ 'attention and chunk arithmetic.' % cause, changes=changes,numerical_class='same-shape-ff-recompute' if recompute_recovery else 'placement-only',measurement=failure, ram_recovery=ram_recovery)diff --git a/freevideo_engine/decode.py b/freevideo_engine/decode.pyindex 052ba94..5dd1651 100644--- a/freevideo_engine/decode.py+++ b/freevideo_engine/decode.py@@ -15,7 +15,7 @@ def decode_to_file(latents, audio_latents, out_path, *, base, offload=False, prepreload=False, pin_weights=False, artifacts_dir=None, phase_callback=None,stream_output=False, stream_weights=False, resident_blocks=0, model_cache=None,linear_compute_cache=False):- from diffusers import AutoencoderKLMiniMaxH3, AutoencoderKLMiniMaxH3Audio+ from diffusers import AutoencoderKLMiniMaxH3from diffusers.utils.export_utils import encode_videofrom src.inference.render import PIXEL_MEAN, PIXEL_STD, FPS@@ -46,61 +46,28 @@ def decode_to_file(latents, audio_latents, out_path, *, base, offload=False, prevae = model_cache.take('video_vae', vae_key)vae_cache_hit = vae is not Noneif vae is None:- if linear_compute_cache:- from .vae_weights import load_video_decoder- layers = AutoencoderKLMiniMaxH3.load_config(- str(Path(base)/'vae'), local_files_only=True)['decoder_num_layers']- count = resident_blocks if offload else layers- if stream_weights:- from .streamed_weights import SafetensorLayers- weight_source = SafetensorLayers((Path(base)/'vae').glob('*.safetensors'),- [f'decoder.transformer_blocks.{index}.' for index in range(count, layers)],- intermediate_dtype=torch.float32)- vae, compute_cache_metrics = load_video_decoder(base, resident_blocks=count,- weight_source=weight_source)- else:- # Diffusers' default safetensors loader uses mmap. Clean mappings- # are reclaimable on Linux, but Windows charges the section view- # against system commit until every tensor/view is gone. Decode- # happens after sampling has already consumed most of the budget,- # so make this one-shot VAE load bounded on Windows as well.- from .system import windows- options = {'disable_mmap': True} if windows() else {}- try:- vae = AutoencoderKLMiniMaxH3.from_pretrained(- str(base), subfolder='vae', local_files_only=True, **options)- except TypeError as error:- if options and 'disable_mmap' in str(error):- raise RuntimeError(- 'The Windows runtime needs a Diffusers build with disable_mmap support; rerun setup.') from error- raise+ # Decode runs after sampling has consumed most of the RAM budget.+ # from_pretrained would hold the whole 9.7 GiB VAE on the CPU (Windows:+ # whole 4.71 GiB shard reads); read only decoder tensors, one at a time,+ # straight to their device. Without the Linear cache all stay FP32.+ from .vae_weights import load_video_decoder+ layers = AutoencoderKLMiniMaxH3.load_config(+ str(Path(base)/'vae'), local_files_only=True)['decoder_num_layers']+ count = resident_blocks if offload else layers+ if stream_weights:+ from .streamed_weights import SafetensorLayers+ weight_source = SafetensorLayers((Path(base)/'vae').glob('*.safetensors'),+ [f'decoder.transformer_blocks.{index}.' for index in range(count, layers)],+ intermediate_dtype=torch.float32 if linear_compute_cache else None)+ vae, compute_cache_metrics = load_video_decoder(base, resident_blocks=count, weight_source=weight_source,+ linear_fp16=linear_compute_cache)vae.eval().requires_grad_(False)if type(resident_blocks) is not int or not 0 <= resident_blocks <= len(vae.decoder.transformer_blocks):raise ValueError('VAE resident block count is outside this decoder')vae.encoder = Nonevae.quant_conv = None- if stream_weights and weight_source is None:- from .streamed_weights import SafetensorLayers- weight_source = SafetensorLayers((Path(base)/'vae').glob('*.safetensors'),- [f'decoder.transformer_blocks.{index}.' for index in range(resident_blocks, len(vae.decoder.transformer_blocks))])- # Generation only uses the decoder; release unused encoder mappings.vae.post_quant_conv.to('cuda')if offload:- if resident_blocks and not linear_compute_cache:- from .streamed_weights import SafetensorLayers- from .offload import cpu_weights- # Read through short-lived mappings. Reading from the loader's- # shared shard mapping would keep already-uploaded pages resident- # on the host while unrelated offloaded tensors still refer to it.- resident_source = SafetensorLayers((Path(base)/'vae').glob('*.safetensors'),- [f'decoder.transformer_blocks.{index}.' for index in range(resident_blocks)])- for index, block in enumerate(list(vae.decoder.transformer_blocks)[:resident_blocks]):- layout = [(value, name, value.dtype, 0, value.numel(), value.shape)- for name, value in cpu_weights(block)]- with resident_source.layer(index, layout) as weights:- for parameter, name, *_ in layout:- parameter.data = weights[name].to('cuda')- del resident_source, layout, weights, parameter, blockfor name, child in vae.decoder.named_children():if name != 'transformer_blocks':child.to('cuda')@@ -214,16 +181,8 @@ def decode_to_file(latents, audio_latents, out_path, *, base, offload=False, premodel_cache.make_room('audio_vae', 1*2**30, model=audio_vae, ram_need=256*2**20)audio_cache_hit = audio_vae is not Noneif audio_vae is None:- from .system import windows- options = {'disable_mmap': True} if windows() else {}- try:- audio_vae = AutoencoderKLMiniMaxH3Audio.from_pretrained(- str(base), subfolder='audio_vae', local_files_only=True, **options).to('cuda')- except TypeError as error:- if options and 'disable_mmap' in str(error):- raise RuntimeError(- 'The Windows runtime needs a Diffusers build with disable_mmap support; rerun setup.') from error- raise+ from .vae_weights import load_audio_vae+ audio_vae, _ = load_audio_vae(base)if model_cache is not None:model_cache.put('audio_vae', audio_key, audio_vae)audio_vae.eval().requires_grad_(False)diff --git a/freevideo_engine/encode_worker.py b/freevideo_engine/encode_worker.pyindex 209d92f..b149576 100644--- a/freevideo_engine/encode_worker.py+++ b/freevideo_engine/encode_worker.py@@ -366,20 +366,16 @@ def _encode(args, request, resident, trace):comfy.model_management.unload_all_models()gc.collect()comfy.model_management.soft_empty_cache()- from diffusers import AutoencoderKLMiniMaxH3from diffusers.modular_pipelines.minimax_h3.encoders import encode_vae_condition+ from .vae_weights import load_video_encoderfrom src.inference.render import PIXEL_MEAN, PIXEL_STDvae_started = time.perf_counter()if request.get('metrics'):save(request['metrics'], {**loading, 'success': False, 'phase': 'keyframe_vae','load_seconds': load_seconds, 'prompt_encode_seconds': prompt_encode_seconds})- vae = AutoencoderKLMiniMaxH3.from_pretrained(request['base'], subfolder='vae')- vae.decoder = None- vae.post_quant_conv = None- if resident is not None:- resident.input_vae_room(vae, dict(width=width, height=height))- vae.to('cuda')- vae.eval().requires_grad_(False)+ # Only the encoder is read; the decoder in the shared shards is skipped.+ vae, _ = load_video_encoder(request['base'], before_upload=None if resident is None else+ lambda model: resident.input_vae_room(model, dict(width=width, height=height)))torch.cuda.synchronize()keyframe_metrics['keyframe_vae_load_seconds'] = time.perf_counter() - vae_startedvae_started = time.perf_counter()diff --git a/freevideo_engine/media_encoding.py b/freevideo_engine/media_encoding.pyindex 162a469..a113db9 100644--- a/freevideo_engine/media_encoding.py+++ b/freevideo_engine/media_encoding.py@@ -157,21 +157,16 @@ def encode_latents(normalized, value, base, canvas, *, resident=None):import gcimport numpy as npimport torch- from diffusers import AutoencoderKLMiniMaxH3, AutoencoderKLMiniMaxH3Audiofrom diffusers.modular_pipelines.minimax_h3.encoders import encode_vae_condition+ from .vae_weights import load_audio_vae, load_video_encoderfrom src.inference.render import PIXEL_MEAN, PIXEL_STDrefs = [{'kind': row['kind']} for row in normalized]if any(row.get('pixels') for row in normalized):print(json.dumps({'event': 'media_encode_phase', 'phase': 'Encoding image/video references'}), flush=True)- vae = AutoencoderKLMiniMaxH3.from_pretrained(base, subfolder='vae')- # Conditioning never decodes. Drop unused decoder weights before CUDA- # placement; the independent output decoder is loaded after sampling.- vae.decoder = None- vae.post_quant_conv = None- if resident is not None:- resident.input_vae_room(vae, canvas)- vae.to('cuda')- vae.eval().requires_grad_(False)+ # Conditioning never decodes: the 9.0 GiB decoder in the shared shards+ # is not read. The independent output decoder is loaded after sampling.+ vae, _ = load_video_encoder(base, before_upload=None if resident is None else+ lambda model: resident.input_vae_room(model, canvas))for row, ref in zip(normalized, refs):if row.get('pixels'):mapped = np.load(row['pixels'], mmap_mode='r', allow_pickle=False)@@ -189,11 +184,8 @@ def encode_latents(normalized, value, base, canvas, *, resident=None):torch.cuda.empty_cache()if any(row.get('audio') for row in normalized):print(json.dumps({'event': 'media_encode_phase', 'phase': 'Encoding reference audio'}), flush=True)- vae = AutoencoderKLMiniMaxH3Audio.from_pretrained(base, subfolder='audio_vae')- if resident is not None:- resident.input_vae_room(vae, canvas, audio=True)- vae.to('cuda')- vae.eval().requires_grad_(False)+ vae, _ = load_audio_vae(base, before_upload=None if resident is None else+ lambda model: resident.input_vae_room(model, canvas, audio=True))mean = torch.tensor(vae.config.latents_mean).view(1, 1, -1)std = torch.tensor(vae.config.latents_std).view(1, 1, -1)if vae.config.sampling_rate != 32000:diff --git a/freevideo_engine/vae_weights.py b/freevideo_engine/vae_weights.pyindex d8d2d69..83a91ed 100644--- a/freevideo_engine/vae_weights.py+++ b/freevideo_engine/vae_weights.py@@ -1,89 +1,210 @@-"""Bounded preparation of H3 decoder Linear weights for FP16 autocast.+"""Bounded loading of the H3 video and audio VAEs, one tensor at a time.-This is an explicit experiment, not a blanket VAE precision change. RMSNorm,-LayerNorm, residual scales, register tokens and post-quantization stay FP32.-Original checkpoint bytes and the encoder used for input images are untouched.+Diffusers' from_pretrained first builds a complete CPU state dictionary. With+disable_mmap it reads each 4.71 GiB video VAE shard whole; its default+copy-on-write mapping is charged to Windows commit. Conditioning also reads+the 9.0 GiB decoder only to discard it. These loaders build the same model,+read only the selected tensors and place each directly on its target device.+The FP32 loads keep from_pretrained's reader per platform: copy-on-write+mappings on Linux, pread on Windows, where a mapping is charged in full.++Values and dtypes match from_pretrained. The one explicit experiment is the+optional decoder Linear compute cache: Linear weights are stored as FP16 for+autocast, while RMSNorm, LayerNorm, residual scales, register tokens and+post-quantization stay FP32. Original checkpoint bytes are untouched."""+from contextlib import contextmanagerfrom pathlib import Path-def load_parameters(model, paths, *, device_for_name):- """Read one tensor at a time, with no retained full FP32 state dictionary.+# The initializers from_pretrained skips while constructing its skeleton.+_INITIALIZERS = ('uniform_', 'normal_', 'trunc_normal_', 'constant_', 'xavier_uniform_', 'xavier_normal_',+ 'kaiming_uniform_', 'kaiming_normal_', 'uniform', 'normal', 'xavier_uniform',+ 'xavier_normal', 'kaiming_uniform', 'kaiming_normal')+++@contextmanager+def parameters_on_meta():+ """Construct a model as from_pretrained does: parameters on meta, buffers real.++ Each parameter moves to meta as it is registered, so neither storage nor+ initialization is spent on it. Buffers and other constructor-computed+ tensors keep their real CPU values: the decoder's RoPE frequencies are+ not stored in the checkpoint.+ """+ import torch+ register = torch.nn.Module.register_parameter+ initializers = {name: getattr(torch.nn.init, name) for name in _INITIALIZERS if hasattr(torch.nn.init, name)}++ def register_on_meta(module, name, param):+ register(module, name, param)+ if param is not None:+ value = module._parameters[name]+ options = dict(value.__dict__, requires_grad=param.requires_grad)+ module._parameters[name] = type(value)(value.to('meta'), **options)++ def skip(tensor, *args, **kwargs):+ return tensor++ torch.nn.Module.register_parameter = register_on_meta+ for name in initializers:+ setattr(torch.nn.init, name, skip)+ try:+ yield+ finally:+ torch.nn.Module.register_parameter = register+ for name, function in initializers.items():+ setattr(torch.nn.init, name, function)+++def skeleton(cls, directory):+ config = cls.load_config(str(directory), local_files_only=True)+ with parameters_on_meta():+ return cls.from_config(config)+++def _file_order(path):+ """Tensor names by data offset, so a seek-bound disk reads each shard forward."""+ import json+ import struct+ with Path(path).open('rb') as stream:+ length = struct.unpack('<Q', stream.read(8))[0]+ if not 2 <= length <= min(100_000_000, Path(path).stat().st_size - 8):+ raise ValueError('Invalid safetensors header size')+ header = json.loads(stream.read(length))+ header.pop('__metadata__', None)+ return sorted(header, key=lambda name: header[name]['data_offsets'][0])+++def _owns_storage(tensor):+ return tensor.storage_offset() == 0 and tensor.untyped_storage().nbytes() == tensor.numel() * tensor.element_size()+++def load_state(model, paths, *, device_for_name, skip=(), linear_dtype=None, mapped=False):+ """Read one tensor at a time, with no retained full state dictionary.++ Each parameter and persistent buffer of `model` comes from exactly one+ checkpoint tensor; checkpoint names under `skip` belong to removed modules+ and are not read. All keys and shapes are checked before reading payloads,+ and a file that changes while it is read fails closed. Values take the+ skeleton's dtype first, as from_pretrained does, so a non-FP32 checkpoint+ keeps that rounding step. `linear_dtype` additionally stores Linear+ parameters in that dtype. A 'meta' placement records only metadata.- CPU tensors are copied even when their dtype is unchanged, so a tiny norm- parameter cannot retain the mapping containing gigabytes of consumed weights.- All shapes/keys are checked before reading payloads; changed files fail closed.+ By default every tensor is read with pread: no file mapping exists, which+ Windows would charge to commit in full, and a CPU tensor owns exactly its+ bytes. `mapped` reads through copy-on-write mappings as from_pretrained+ does on Linux, without its extra copy: CPU tensors stay views of one+ long-lived mapping (clean page cache the kernel can reclaim and the RAM+ guard credits), and uploads use a short-lived mapping per shard, so their+ pages do not stay mapped."""import torch+ from safetensors import safe_openfrom .tensor_io import open_tensors- expected = dict(model.named_parameters())+ expected = dict(model.state_dict(keep_vars=True))+ skip = tuple(skip)files, sources = {}, {}for path in sorted(Path(p) for p in paths):stamp = path.stat()files[path] = (stamp.st_size, stamp.st_mtime_ns, stamp.st_ctime_ns)with open_tensors(str(path), framework='pt') as handle:for name in handle.keys():- if name.startswith(('encoder.', 'quant_conv.')):+ if name.startswith(skip):continueif name not in expected or name in sources:- raise ValueError('Unexpected or duplicate VAE decoder weight: ' + name)+ raise ValueError('Unexpected or duplicate VAE weight: ' + name)metadata = handle.get_slice(name)if tuple(metadata.get_shape()) != tuple(expected[name].shape):- raise ValueError('VAE decoder weight shape mismatch: ' + name)+ raise ValueError('VAE weight shape mismatch: ' + name)if not (metadata.get_dtype().startswith('F') or metadata.get_dtype() == 'BF16'):raise ValueError('VAE weight is not floating point: ' + name)sources[name] = pathif set(sources) != set(expected):- raise ValueError('Missing VAE decoder weights: ' + ', '.join(sorted(set(expected) - set(sources))))- converted, loaded, streamed_count, streamed_bytes = 0, 0, 0, 0+ raise ValueError('Missing VAE weights: ' + ', '.join(sorted(set(expected) - set(sources))))+ converted, loaded, mapped_bytes, streamed_count, streamed_bytes = 0, 0, 0, 0, 0for path, stamp in files.items():- names = [name for name, source in sources.items() if source == path]+ names = [name for name in _file_order(path) if sources.get(name) == path]if not names:continue- for name in names:- parent, _, leaf = name.rpartition('.')- owner = model.get_submodule(parent) if parent else model- dtype = torch.float16 if isinstance(owner, torch.nn.Linear) else torch.float32- device = torch.device(device_for_name(name))- if device.type == 'meta':- # Only metadata is needed until a streamed layer executes.- # Reading the whole CPU remainder here defeats streaming even- # if its storage is discarded by the later offloader.- target = torch.empty(expected[name].shape, dtype=dtype, device='meta')- owner._parameters[leaf] = torch.nn.Parameter(target, requires_grad=False)- streamed_count += 1- streamed_bytes += target.numel() * target.element_size()- continue- # A long-lived shard handle keeps consumed pages mapped even after- # individual tensors are released. Close it after every upload.- with open_tensors(str(path), framework='pt') as handle:- source = handle.get_tensor(name)- if not source.is_floating_point():- raise ValueError('VAE weight is not floating point: ' + name)- # Match from_pretrained's FP32 parameter dtype before autocast,- # including the rounding of a non-FP32 checkpoint tensor.- target = source.to(dtype=torch.float32).to(device=device, dtype=dtype, copy=True)- owner._parameters[leaf] = torch.nn.Parameter(target, requires_grad=False)- converted += int(dtype == torch.float16)- loaded += target.numel() * target.element_size()- del source, target+ # A pread reader owns only each requested tensor's bytes and keeps no+ # file mapping, so one handle per shard retains nothing consumed.+ with (safe_open(str(path), framework='pt', device='cpu') if mapped+ else open_tensors(str(path), framework='pt')) as handle:+ views = None+ for name in names:+ parent, _, leaf = name.rpartition('.')+ owner = model.get_submodule(parent) if parent else model+ reference = expected[name]+ parameter = leaf in owner._parameters+ dtype = (linear_dtype if linear_dtype is not None and parameter+ and isinstance(owner, torch.nn.Linear) else reference.dtype)+ device = torch.device(device_for_name(name))+ if device.type == 'meta':+ # Only metadata is needed until a streamed layer executes.+ # Reading the whole CPU remainder here defeats streaming even+ # if its storage is discarded by the later offloader.+ target = torch.empty(reference.shape, dtype=dtype, device='meta')+ streamed_count += 1+ streamed_bytes += target.numel() * target.element_size()+ else:+ view = mapped and device.type == 'cpu'+ if view and views is None:+ views = safe_open(str(path), framework='pt', device='cpu')+ source = (views if view else handle).get_tensor(name)+ if not source.is_floating_point():+ raise ValueError('VAE weight is not floating point: ' + name)+ # from_pretrained converts to the skeleton's dtype, including+ # the rounding of a non-FP32 checkpoint tensor, before any cache.+ value = source.to(dtype=reference.dtype)+ # Otherwise a CPU result is copied unless it owns exactly its+ # own bytes, so a small tensor never retains a read buffer.+ target = value.to(device=device, dtype=dtype, copy=device.type == 'cpu' and not view+ and not _owns_storage(value))+ converted += int(dtype != reference.dtype)+ loaded += target.numel() * target.element_size()+ mapped_bytes += target.numel() * target.element_size() if view and target is source else 0+ del source, value+ if parameter:+ owner._parameters[leaf] = torch.nn.Parameter(target, requires_grad=False)+ else:+ owner._buffers[leaf] = target+ del target+ del viewscurrent = path.stat()if (current.st_size, current.st_mtime_ns, current.st_ctime_ns) != stamp:raise ValueError('VAE checkpoint changed during preparation: ' + str(path))+ cached = linear_dtype is not Nonereturn dict(linear_parameter_count=converted, prepared_parameter_bytes=loaded,+ mapped_parameter_bytes=mapped_bytes,streamed_parameter_count=streamed_count, streamed_parameter_bytes=streamed_bytes,source_policy='Original FP32 checkpoint, one tensor at a time',- compute_policy='FP16 Linear weights; FP32 normalization, residual scales and other parameters')+ compute_policy=('FP16 Linear weights; FP32 normalization, residual scales and other parameters'+ if cached else 'Original FP32 parameters'))-def load_video_decoder(base, *, resident_blocks, weight_source=None):- """Place the selected decoder prefix directly on CUDA without a CPU copy."""+def load_parameters(model, paths, *, device_for_name, linear_fp16=True, mapped=False):+ """The decoder side of the shared video VAE shards; encoder tensors are not read."""import torch+ return load_state(model, paths, device_for_name=device_for_name, skip=('encoder.', 'quant_conv.'),+ linear_dtype=torch.float16 if linear_fp16 else None, mapped=mapped)+++def _mapped():+ """from_pretrained's reader on this platform: mapped on Linux, never on Windows."""+ from .system import windows+ return not windows()+++def load_video_decoder(base, *, resident_blocks, weight_source=None, linear_fp16=True, device='cuda'):+ """Place the selected decoder prefix directly on CUDA without a CPU copy.++ Later blocks stay on the CPU, or bind to `weight_source` without reading.+ Without the Linear cache every parameter keeps from_pretrained's FP32.+ """from diffusers import AutoencoderKLMiniMaxH3directory = Path(base) / 'vae'- config = AutoencoderKLMiniMaxH3.load_config(str(directory), local_files_only=True)- with torch.device('meta'):- model = AutoencoderKLMiniMaxH3.from_config(config)+ model = skeleton(AutoencoderKLMiniMaxH3, directory)if type(resident_blocks) is not int or not 0 <= resident_blocks <= len(model.decoder.transformer_blocks):raise ValueError('Invalid VAE resident block count')if weight_source is not None and weight_source.prefixes != tuple(@@ -92,22 +213,55 @@ def load_video_decoder(base, *, resident_blocks, weight_source=None):raise ValueError('Streamed VAE source does not match the offloaded layer order')model.encoder = Nonemodel.quant_conv = None- # The pinned decoder has one non-persistent buffer, generated by its own- # constructor rather than read from the checkpoint. Preserve its FP32 math.- model.decoder.rope = type(model.decoder.rope)(- int(model.config.decoder_attention_head_dim * model.config.decoder_rope_dim_ratio),- theta=model.config.decoder_rope_theta)if any(value.is_meta for value in model.buffers()):raise ValueError('Unexpected unmaterialized VAE buffer')def placement(name):prefix = 'decoder.transformer_blocks.'if name.startswith(prefix) and int(name[len(prefix):].split('.', 1)[0]) >= resident_blocks:return 'meta' if weight_source is not None else 'cpu'- return 'cuda'- metrics = load_parameters(model, directory.glob('*.safetensors'), device_for_name=placement)+ return device+ # The FP32 decoder keeps from_pretrained's storage and reads on each+ # platform. On Linux offloaded CPU blocks stay clean mapped page cache,+ # which the RAM guard credits and the kernel can reclaim; Windows would+ # charge a mapping whole to commit, so there they are private copies, as+ # disable_mmap made them. The Linear cache converts every tensor it reads.+ metrics = load_parameters(model, directory.glob('*.safetensors'), device_for_name=placement,+ linear_fp16=linear_fp16, mapped=not linear_fp16 and _mapped())if weight_source is not None:from .offload import initialize_streamed_layerfor index, layer in enumerate(list(model.decoder.transformer_blocks)[resident_blocks:]):initialize_streamed_layer(layer, weight_source, index)model.eval().requires_grad_(False)return model, metrics+++def load_video_encoder(base, *, before_upload=None, device='cuda'):+ """The conditioning encoder and quant_conv in FP32; decoder tensors are not read.++ `before_upload(model)` runs on the meta-parameter model, whose tensor sizes+ are final, before any weight reaches the device.+ """+ from diffusers import AutoencoderKLMiniMaxH3+ directory = Path(base) / 'vae'+ model = skeleton(AutoencoderKLMiniMaxH3, directory)+ model.decoder = None+ model.post_quant_conv = None+ if before_upload is not None:+ before_upload(model)+ metrics = load_state(model, directory.glob('*.safetensors'), device_for_name=lambda name: device,+ skip=('decoder.', 'post_quant_conv.'), mapped=_mapped())+ model.to(device).eval().requires_grad_(False)+ return model, metrics+++def load_audio_vae(base, *, before_upload=None, device='cuda'):+ """The complete audio VAE in FP32, including the buffers stored in its checkpoint."""+ from diffusers import AutoencoderKLMiniMaxH3Audio+ directory = Path(base) / 'audio_vae'+ model = skeleton(AutoencoderKLMiniMaxH3Audio, directory)+ if before_upload is not None:+ before_upload(model)+ metrics = load_state(model, directory.glob('*.safetensors'), device_for_name=lambda name: device,+ mapped=_mapped())+ model.to(device).eval().requires_grad_(False)+ return model, metrics