Repository navigation
feat(mps): support MiniMax-H3 INT8 inference on Apple M5 #1672
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
q6y6y6
wants to merge
3
commits into
ModelTC:main
Choose a base branch
from
q6y6y6:feat/minimax-h3-int8-mps
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| { | ||
| "infer_steps": 4, | ||
| "num_frames": 124, | ||
| "size": [ | ||
| 544, | ||
| 960 | ||
| ], | ||
| "fps": 24, | ||
| "enable_cfg": false, | ||
| "cpu_offload": false, | ||
| "offload_granularity": "model", | ||
| "use_adaln_cache": false, | ||
| "text_encoder_cpu_offload": false, | ||
| "text_encoder_offload_granularity": "model", | ||
| "vae_cpu_offload": false, | ||
| "attn_type": "torch_sdpa_mps", | ||
| "rms_type": "torch_native", | ||
| "rope_type": "torch_real_rope", | ||
| "feature_caching": "NoCaching", | ||
| "use_compile": false, | ||
| "video_flow_shift": 6.0, | ||
| "audio_flow_shift": 3.0, | ||
| "h3_step_update": "training_euler", | ||
| "vae_spatial_scale_factor": 16, | ||
| "model_cls": "minimax_h3", | ||
| "model_variant": "fl2av", | ||
| "task": "t2av", | ||
| "local_files_only": true, | ||
| "mps_sdpa_query_chunk_size": 512, | ||
| "rope_compute_dtype": "bf16", | ||
| "dit_disk_streaming": false, | ||
| "text_encoder_disk_streaming": false, | ||
| "text_encoder_release_block_offload_buffers": false, | ||
| "warmup": false, | ||
| "lazy_load": false, | ||
| "shared_cpu_weights": false, | ||
| "tensor_parallel": false, | ||
| "text_encoder_tensor_parallel": false, | ||
| "seq_parallel": false, | ||
| "cfg_parallel": false, | ||
| "dit_release_block_offload_buffers": false, | ||
| "unload_modules": false, | ||
| "cpu_offload_block_contiguous": false, | ||
| "dit_quantized": true, | ||
| "dit_quant_scheme": "int8-metal", | ||
| "use_fused_qkv": false, | ||
| "text_encoder_shared_cpu_weights": false, | ||
| "text_encoder_quantized": false, | ||
| "text_encoder_load_on_init": true, | ||
| "video_vae_offload_granularity": "model", | ||
| "video_vae_shared_cpu_weights": false, | ||
| "video_vae_quantized": false, | ||
| "vae_use_compile": false, | ||
| "vae_encoder_conv_mode": "torch", | ||
| "vae_sensitive_layer_dtype": "fp32", | ||
| "vae_attn_type": "torch_sdpa", | ||
| "parallel": false, | ||
| "dit_quant_scope": "dit_proj", | ||
| "mps_resident_weights": true, | ||
| "text_encoder_load_vision_on_init": false | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| """Load resident weight containers directly into CPU-visible MPS storage.""" | ||
|
|
||
| import torch | ||
| from loguru import logger | ||
|
|
||
| from lightx2v.common.offload.mps_manager import host_view | ||
|
|
||
|
|
||
| def weight_bindings(root): | ||
| seen, stack = set(), [root] | ||
| while stack: | ||
| obj = stack.pop() | ||
| if obj is None or id(obj) in seen: | ||
| continue | ||
| seen.add(id(obj)) | ||
| stack.extend(getattr(obj, "_modules", {}).values()) | ||
| stack.extend(getattr(obj, "_parameters", {}).values()) | ||
| for name, attr, transpose in getattr(obj, "base_attrs", ()): | ||
| if attr == "weight": | ||
| transpose = getattr(obj, "weight_need_transpose", transpose) | ||
| yield obj, name, attr, transpose | ||
|
|
||
|
|
||
| def load_resident_groups(checkpoint, groups): | ||
| """Adopt exact checkpoint dtypes, with no retained host weight copies. | ||
|
|
||
| Groups must partition the selected checkpoint. CPU aliases exist only while | ||
| reading idle allocations; synchronization orders both sides of host writes. | ||
| Container.load must adopt storage or a transpose view without conversion. | ||
| """ | ||
| groups = list(groups) | ||
| names = [name for _, root in groups for _, name, _, _ in weight_bindings(root)] | ||
| if len(names) != len(set(names)) or set(names) != set(checkpoint.weight_map): | ||
| raise ValueError("Resident checkpoint and model bindings must match exactly") | ||
| total = 0 | ||
| for label, root in groups: | ||
| bindings = list(weight_bindings(root)) | ||
| tensors = {} | ||
| for _, name, _, _ in bindings: | ||
| dtype, shape, _, size = checkpoint.tensor_metadata(name) | ||
| tensors[name] = torch.empty(shape, dtype=dtype, device="mps") | ||
| total += size | ||
| torch.mps.synchronize() | ||
| aliases = {name: host_view(tensor) for name, tensor in tensors.items()} | ||
| checkpoint.load_tensors_into(aliases) | ||
| torch.mps.synchronize() | ||
| del aliases | ||
| root.load(tensors) | ||
| for obj, name, attr, transpose in bindings: | ||
| actual, original = getattr(obj, attr, None), tensors[name] | ||
| shape = tuple(reversed(original.shape)) if transpose else tuple(original.shape) | ||
| if ( | ||
| not isinstance(actual, torch.Tensor) | ||
| or actual.device.type != "mps" | ||
| or actual.dtype != original.dtype | ||
| or tuple(actual.shape) != shape | ||
| or actual.untyped_storage()._cdata != original.untyped_storage()._cdata | ||
| or getattr(obj, "pin_" + attr, None) is not None | ||
| ): | ||
| raise RuntimeError("Resident loader requires exact storage adoption: " + name) | ||
| logger.info("MPS resident {} loaded; {:.3f} GiB cumulative weights", label, total / 1024**3) | ||
| return {"weight_bytes": total, "weight_count": len(names)} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| """Mixed-precision selection and checkpoint contract for H3 Apple INT8.""" | ||
|
|
||
| import json | ||
| from pathlib import Path | ||
|
|
||
| MLP_SUFFIXES = (".ff.net.0.proj", ".ff.net.2") | ||
| QUANT_SCOPES = { | ||
| "fc1": ("fc1",), | ||
| "fc2": ("fc2",), | ||
| "mlp": ("fc1", "fc2"), | ||
| "mlp_out": ("fc1", "fc2", "out"), | ||
| "mlp_qkv": ("fc1", "fc2", "qkv"), | ||
| "dit_proj": ("fc1", "fc2", "qkv", "out"), | ||
| } | ||
|
|
||
|
|
||
| def linear_component(name): | ||
| if not name.startswith("transformer_blocks."): | ||
| return None | ||
| if name.endswith(".ff.net.0.proj"): | ||
| return "fc1" | ||
| if name.endswith(".ff.net.2"): | ||
| return "fc2" | ||
| if name.endswith((".attn.to_q", ".attn.to_k", ".attn.to_v")): | ||
| return "qkv" | ||
| if name.endswith(".attn.to_out.0"): | ||
| return "out" | ||
| return None | ||
|
|
||
|
|
||
| def is_mlp_linear(name): | ||
| return name.startswith("transformer_blocks.") and name.endswith(MLP_SUFFIXES) | ||
|
|
||
|
|
||
| def linear_quant_scheme(config, name): | ||
| scheme = config.get("dit_quant_scheme", "Default") | ||
| scope = config.get("dit_quant_scope", "all") | ||
| if scope == "all": | ||
| return scheme | ||
| if scope not in QUANT_SCOPES or scheme != "int8-metal": | ||
| raise ValueError("H3 dit_quant_scope supports all, or an explicit int8-metal projection profile") | ||
| return scheme if linear_component(name) in QUANT_SCOPES[scope] else "Default" | ||
|
|
||
|
|
||
| def validate_metal_checkpoint(config): | ||
| path = Path(config["dit_quantized_ckpt"]) | ||
| indices = list(path.glob("*.safetensors.index.json")) if path.is_dir() else [] | ||
| if len(indices) != 1: | ||
| raise ValueError("H3 int8-metal requires one indexed safetensors checkpoint directory") | ||
| index = json.loads(indices[0].read_text()) | ||
| metadata = index.get("metadata", {}) | ||
| if metadata.get("lightx2v_quant_scheme") != "int8-metal": | ||
| raise ValueError("H3 checkpoint does not declare lightx2v_quant_scheme=int8-metal") | ||
| if metadata.get("lightx2v_quant_scope") != config.get("dit_quant_scope", "all"): | ||
| raise ValueError("H3 INT8 checkpoint scope does not match dit_quant_scope") | ||
| import torch | ||
|
|
||
| from lightx2v.common.offload.safetensors_checkpoint import SafetensorsCheckpoint | ||
|
|
||
| checkpoint = SafetensorsCheckpoint(path, weight_map=index["weight_map"]) | ||
| scope = config.get("dit_quant_scope", "all") | ||
| selected = set() | ||
| for name in checkpoint.weight_map: | ||
| dtype, shape, _, _ = checkpoint.tensor_metadata(name) | ||
| if name.endswith(".weight") and linear_quant_scheme(dict(config, dit_quant_scheme="int8-metal"), name[:-7]) == "int8-metal": | ||
| # Explicit scopes select only their declared projections. | ||
| if scope == "all" and linear_component(name[:-7]) is None: | ||
| continue | ||
| if dtype != torch.int8 or len(shape) != 2 or any(n <= 0 or n % 128 for n in shape): | ||
| raise ValueError("Invalid INT8 Metal weight shape/dtype: " + name) | ||
| scale = name + "_scale" | ||
| if scale not in checkpoint.weight_map: | ||
| raise ValueError("Missing INT8 Metal scale: " + scale) | ||
| sdtype, sshape, _, _ = checkpoint.tensor_metadata(scale) | ||
| if sdtype != torch.float32 or sshape != (shape[0], 1): | ||
| raise ValueError("Invalid INT8 Metal scale shape/dtype: " + scale) | ||
| selected.add(name) | ||
| elif dtype == torch.int8: | ||
| raise ValueError("INT8 tensor outside declared projection scope: " + name) | ||
| if not selected: | ||
| raise ValueError("No INT8 weights in declared H3 projection scope") | ||
| if metadata.get("quantized_linear_count", len(selected)) != len(selected): | ||
| raise ValueError("Declared INT8 projection count does not match checkpoint") | ||
| return index | ||
|
|
||
|
|
||
| def load_metal_checkpoint(config, device, remove_keys=()): | ||
| """Honor the authoritative index, including selective checkpoint views.""" | ||
| from collections import defaultdict | ||
|
|
||
| from safetensors import safe_open | ||
|
|
||
| index = validate_metal_checkpoint(config) | ||
| root = Path(config["dit_quantized_ckpt"]) | ||
| by_file = defaultdict(list) | ||
| for name, file in index["weight_map"].items(): | ||
| if not any(part in name for part in remove_keys): | ||
| by_file[file].append(name) | ||
| tensors = {} | ||
| for file, names in sorted(by_file.items()): | ||
| with safe_open(str(root / file), framework="pt", device="cpu") as source: | ||
| for name in names: | ||
| tensors[name] = source.get_tensor(name).to(device) | ||
| return tensors |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: ModelTC/LightX2V
Length of output: 43071
Script executed:
Repository: ModelTC/LightX2V
Length of output: 19255
Script executed:
Repository: ModelTC/LightX2V
Length of output: 17326
Script executed:
Repository: ModelTC/LightX2V
Length of output: 19181
Script executed:
Repository: ModelTC/LightX2V
Length of output: 12430
Resolve FP8 fused imports before compilation.
The first fused invocation can import Triton and register custom operators while
torch.compiletraces the WAN or H3 block. Resolve the GELU imports in the fusion-enabled wrapper constructors. Resolve the SwiGLU import in the H3 setup path before compiling the block. Keep these imports gated so MPS paths do not load CUDA modules.For the GELU wrappers, use the stored module from
apply:Suggested fix
class GeluLinear: def __init__(self, module, fusion=None): self.module = module self.fusion = fusion + self._fused = None self.weight = getattr(module, "weight", None) self.scale = getattr(module, "weight_scale", None) self.bias = getattr(module, "bias", None) self.infer_dtype = getattr(module, "infer_dtype", None) self.activation_qmax = getattr(module, "fp8_activation_qmax", None) if fusion is not None: + from lightx2v.common.ops.mm import fused_gelu_linear + + self._fused = fused_gelu_linear self.device = self.weight.device self.input_dim = self.weight.shape[1 if fusion == "int8-convrot" else 0] def apply(self, hidden): ... if self.fusion == "fp8-sgl": - from lightx2v.common.ops.mm.fused_gelu_linear import fused_gelu_quant_fp8_sgl - - quantized, scale = fused_gelu_quant_fp8_sgl(hidden) + quantized, scale = self._fused.fused_gelu_quant_fp8_sgl(hidden) return sgl_fp8_scaled_mm(quantized, self.weight, scale, self.infer_dtype, self.bias) if self.fusion == "fp8-f16-accum": - from lightx2v.common.ops.mm.fused_gelu_linear import fused_gelu_quant_fp8_f16_accum - - quantized, scale = fused_gelu_quant_fp8_f16_accum(hidden, self.activation_qmax) + quantized, scale = self._fused.fused_gelu_quant_fp8_f16_accum(hidden, self.activation_qmax) return cutlass_scaled_fp8_mm_f16_accum(quantized, self.weight, scale, self.scale, self.infer_dtype, self.bias) ... - from lightx2v.common.ops.mm.fused_gelu_linear import fused_gelu_int8_convrot_linear - - return fused_gelu_int8_convrot_linear(hidden, self.weight, self.scale, self.bias, self.infer_dtype, module._convrot_groupsize) + return self._fused.fused_gelu_int8_convrot_linear(hidden, self.weight, self.scale, self.bias, self.infer_dtype, module._convrot_groupsize)Apply the equivalent stored-reference change to
OffloadedF16GeluLinear. Theprepare_convrot_gelu_fusionimport at lines 244-245 is already in setup and does not need this change.