PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
Implement shard parallelism configuration and update documentation (#1942)
Xin He7e2b69d4d514
diff --git a/auto_round/compressors/model_free.py b/auto_round/compressors/model_free.pyindex 5d2f33453..e9b7abde0 100644--- a/auto_round/compressors/model_free.py+++ b/auto_round/compressors/model_free.py@@ -91,13 +91,14 @@ from __future__ import annotationsimport copyimport json+import multiprocessing as mpimport osimport reimport shutilimport time-from concurrent.futures import ThreadPoolExecutor+from concurrent.futures import ProcessPoolExecutor, as_completedfrom dataclasses import asdict, fields-from typing import Any, Optional, Union+from typing import Any, Callable, Optional, Unionimport torch@@ -637,8 +638,66 @@ def _quantize_single_tensor(return layer_name, {tensor_name: tensor}, None, layer_name+def _collect_mxfp_source_entries(raw_tensors: dict[str, torch.Tensor]) -> list[tuple[str, str, str, int]]:+ """Collect MXFP source tensors present in a shard.++ Returns entries as ``(layer_name, weight_key, scale_key, bits)`` where+ ``bits`` is 8 for ``.weight`` (float8) and 4 for ``.weight_packed``.+ """+ entries: list[tuple[str, str, str, int]] = []+ for name, tensor in raw_tensors.items():+ if name.endswith(".weight") and tensor.dtype == torch.float8_e4m3fn:+ layer_name = name[: -len(".weight")]+ scale_key = f"{layer_name}.weight_scale"+ if scale_key in raw_tensors:+ entries.append((layer_name, name, scale_key, 8))+ elif name.endswith(".weight_packed") and tensor.dtype in (torch.int8, torch.uint8):+ layer_name = name[: -len(".weight_packed")]+ scale_key = f"{layer_name}.weight_scale"+ if scale_key in raw_tensors:+ entries.append((layer_name, name, scale_key, 4))+ return entries+++def _is_out_of_memory_error(exc: Exception) -> bool:+ if isinstance(exc, torch.OutOfMemoryError):+ return True+ message = str(exc).lower()+ return "out of memory" in message or "cuda error: out of memory" in message+++def _dequantize_with_device_fallback(+ *,+ dequant_device: str,+ shard_prefix: str,+ op_name: str,+ tensor_label: str,+ on_device: Callable[[], torch.Tensor],+ on_cpu: Callable[[], torch.Tensor],+) -> torch.Tensor:+ """Run dequantization on ``dequant_device`` and fall back to CPU on errors."""+ if dequant_device != "cpu":+ try:+ return on_device()+ except Exception as e:+ if _is_out_of_memory_error(e):+ logger.warning(+ f"{shard_prefix}{op_name} on {dequant_device} ran OOM for {tensor_label}: {e}. "+ "Clearing accelerator memory and falling back to CPU for this tensor."+ )+ clear_memory()+ else:+ logger.warning(+ f"{shard_prefix}{op_name} on {dequant_device} failed for {tensor_label}: {e}. "+ "Falling back to CPU for this tensor."+ )+ return on_cpu()++def _dequant_mxfp_tensors(raw_tensors: dict[str, torch.Tensor],+ device: str = "cpu",+ shard_name: str | None = None,) -> dict[str, torch.Tensor]:"""Dequantize llm-compressor MXFP8 / MXFP4 weight tensors to bfloat16.@@ -657,44 +716,63 @@ def _dequant_mxfp_tensors(from auto_round_extension.vllm_ext.mxfp4_qdq_utils import to_dtypefrom auto_round_extension.vllm_ext.mxfp8_qdq_utils import dequant_mx_fp8- # Tuple layout: (layer_name, weight_key, scale_key, is_fp8)- entries: list[tuple[str, str, str, bool]] = []- for name, tensor in raw_tensors.items():- if name.endswith(".weight") and tensor.dtype == torch.float8_e4m3fn:- layer_name = name[: -len(".weight")]- scale_key = f"{layer_name}.weight_scale"- if scale_key in raw_tensors:- entries.append((layer_name, name, scale_key, True))- elif name.endswith(".weight_packed") and tensor.dtype in (torch.int8, torch.uint8):- layer_name = name[: -len(".weight_packed")]- scale_key = f"{layer_name}.weight_scale"- if scale_key in raw_tensors:- entries.append((layer_name, name, scale_key, False))+ # Tuple layout: (layer_name, weight_key, scale_key, bits)+ entries = _collect_mxfp_source_entries(raw_tensors)if not entries:return raw_tensors- n_mxfp8 = sum(1 for _layer_name, _weight_key, _scale_key, is_fp8 in entries if is_fp8)+ n_mxfp8 = sum(1 for _layer_name, _weight_key, _scale_key, bits in entries if bits == 8)n_mxfp4 = len(entries) - n_mxfp8- logger.info("Dequantizing MXFP tensor(s) to bfloat16: " f"MXFP8={n_mxfp8}, MXFP4={n_mxfp4}, total={len(entries)}.")+ dequant_device = str(device or "cpu")+ shard_prefix = f"[{shard_name}] " if shard_name else ""+ logger.info(+ f"{shard_prefix}Dequantizing MXFP tensor(s) to bfloat16 on {dequant_device}: "+ f"MXFP8={n_mxfp8}, MXFP4={n_mxfp4}, total={len(entries)}."+ )- for layer_name, weight_key, scale_key, is_fp8 in entries:+ for layer_name, weight_key, scale_key, bits in entries:weight = raw_tensors.pop(weight_key)scale = raw_tensors.pop(scale_key).view(torch.uint8)- if is_fp8:- dq_weight = dequant_mx_fp8(- weight_fp8=weight,- scale_e8m0=scale,- block_size=32,- target_dtype=torch.bfloat16,+ if bits == 8:+ dq_weight = _dequantize_with_device_fallback(+ dequant_device=dequant_device,+ shard_prefix=shard_prefix,+ op_name="MXFP dequant",+ tensor_label=layer_name,+ on_device=lambda: dequant_mx_fp8(+ weight_fp8=weight.to(dequant_device, non_blocking=True),+ scale_e8m0=scale.to(dequant_device, non_blocking=True),+ block_size=32,+ target_dtype=torch.bfloat16,+ ).to("cpu"),+ on_cpu=lambda: dequant_mx_fp8(+ weight_fp8=weight,+ scale_e8m0=scale,+ block_size=32,+ target_dtype=torch.bfloat16,+ ),)else:- dq_weight = to_dtype(- data_lp=weight.view(torch.uint8).contiguous(),- scale_e8m0=scale,- elem_dtype="fp4_e2m1",- block_size=32,- target_dtype=torch.bfloat16,+ dq_weight = _dequantize_with_device_fallback(+ dequant_device=dequant_device,+ shard_prefix=shard_prefix,+ op_name="MXFP dequant",+ tensor_label=layer_name,+ on_device=lambda: to_dtype(+ data_lp=weight.view(torch.uint8).contiguous().to(dequant_device, non_blocking=True),+ scale_e8m0=scale.to(dequant_device, non_blocking=True),+ elem_dtype="fp4_e2m1",+ block_size=32,+ target_dtype=torch.bfloat16,+ ).to("cpu"),+ on_cpu=lambda: to_dtype(+ data_lp=weight.view(torch.uint8).contiguous(),+ scale_e8m0=scale,+ elem_dtype="fp4_e2m1",+ block_size=32,+ target_dtype=torch.bfloat16,+ ),)raw_tensors[f"{layer_name}.weight"] = dq_weight@@ -705,6 +783,8 @@ def _handle_mxfp_source_tensors(raw_tensors: dict[str, torch.Tensor],matcher: "_PatternMatcher",source_state: dict[str, int] | None = None,+ device: str = "cpu",+ shard_name: str | None = None,) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor], list[str]]:"""Handle llm-compressor-style MXFP8/MXFP4 source tensors.@@ -725,23 +805,8 @@ def _handle_mxfp_source_tensors(Returns:``(raw_tensors, passthrough_tensors, passthrough_layers)``."""- # --- collect MXFP8 and MXFP4 entries ---- entries_fp8: list[tuple[str, str, str]] = [] # (layer_name, weight_key, scale_key)- entries_fp4: list[tuple[str, str, str]] = []-- for name, tensor in raw_tensors.items():- if name.endswith(".weight") and tensor.dtype == torch.float8_e4m3fn:- layer_name = name[: -len(".weight")]- scale_key = f"{layer_name}.weight_scale"- if scale_key in raw_tensors:- entries_fp8.append((layer_name, name, scale_key))- elif name.endswith(".weight_packed") and tensor.dtype in (torch.int8, torch.uint8):- layer_name = name[: -len(".weight_packed")]- scale_key = f"{layer_name}.weight_scale"- if scale_key in raw_tensors:- entries_fp4.append((layer_name, name, scale_key))-- if not entries_fp8 and not entries_fp4:+ entries = _collect_mxfp_source_entries(raw_tensors)+ if not entries:return raw_tensors, {}, []source_state = source_state or {}@@ -750,24 +815,12 @@ def _handle_mxfp_source_tensors(passthrough_layers: list[str] = []n_dequant = 0- for layer_name, weight_key, scale_key in entries_fp8:+ for layer_name, weight_key, scale_key, bits in entries:scheme = matcher.resolve_scheme(f"{layer_name}.weight")- target_is_mxfp8 = (- scheme is not None and is_mx_fp((scheme.get("data_type") or "").lower()) and scheme.get("bits") == 8+ target_is_same_mxfp = (+ scheme is not None and is_mx_fp((scheme.get("data_type") or "").lower()) and scheme.get("bits") == bits)- if target_is_mxfp8:- passthrough_tensors[weight_key] = raw_tensors.pop(weight_key).to("cpu")- passthrough_tensors[scale_key] = raw_tensors.pop(scale_key).to("cpu")- passthrough_layers.append(layer_name)- else:- n_dequant += 1-- for layer_name, weight_key, scale_key in entries_fp4:- scheme = matcher.resolve_scheme(f"{layer_name}.weight")- target_is_mxfp4 = (- scheme is not None and is_mx_fp((scheme.get("data_type") or "").lower()) and scheme.get("bits") == 4- )- if target_is_mxfp4:+ if target_is_same_mxfp:passthrough_tensors[weight_key] = raw_tensors.pop(weight_key).to("cpu")passthrough_tensors[scale_key] = raw_tensors.pop(scale_key).to("cpu")passthrough_layers.append(layer_name)@@ -775,7 +828,7 @@ def _handle_mxfp_source_tensors(n_dequant += 1if n_dequant:- raw_tensors = _dequant_mxfp_tensors(raw_tensors)+ raw_tensors = _dequant_mxfp_tensors(raw_tensors, device=device, shard_name=shard_name)parts: list[str] = []if passthrough_layers:@@ -792,6 +845,8 @@ def _handle_mxfp_source_tensors(def _dequant_fp8_tensors(raw_tensors: dict[str, torch.Tensor],block_size: list | None = None,+ device: str = "cpu",+ shard_name: str | None = None,) -> dict[str, torch.Tensor]:"""Dequantize DeepSeek-V3-style FP8 weight tensors to bfloat16.@@ -819,12 +874,32 @@ def _dequant_fp8_tensors(if not quant_entries:return raw_tensors- logger.info(f"Dequantizing {len(quant_entries)} FP8 weight tensor(s) to bfloat16.")+ # device has already been resolved by the caller; use it directly here.+ dequant_device = str(device or "cpu")+ shard_prefix = f"[{shard_name}] " if shard_name else ""++ logger.info(+ f"{shard_prefix}Dequantizing {len(quant_entries)} FP8 weight tensor(s) to bfloat16 on {dequant_device}."+ )for weight_name, scale_name in quant_entries:weight = raw_tensors[weight_name]scale = raw_tensors.pop(scale_name)- raw_tensors[weight_name] = _dequant_fp8_linear_weight(weight, scale, block_size=block_size)++ # Dequantize on GPU for throughput, then move back to CPU to keep+ # per-shard memory usage bounded before per-layer quantization.+ raw_tensors[weight_name] = _dequantize_with_device_fallback(+ dequant_device=dequant_device,+ shard_prefix=shard_prefix,+ op_name="FP8 dequant",+ tensor_label=weight_name,+ on_device=lambda: _dequant_fp8_linear_weight(+ weight.to(dequant_device, non_blocking=True),+ scale.to(dequant_device, non_blocking=True),+ block_size=block_size,+ ).to("cpu"),+ on_cpu=lambda: _dequant_fp8_linear_weight(weight, scale, block_size=block_size),+ )return raw_tensors@@ -836,6 +911,7 @@ def _process_shard(ignore_patterns: list[str] = None,device: str = "cpu",*,+ shard_name: str | None = None,matcher: "_PatternMatcher | None" = None,fp8_block_size: list | None = None,model_type: str | None = None,@@ -913,11 +989,18 @@ def _process_shard(raw_tensors,matcher,source_state=source_state,+ device=device,+ shard_name=shard_name,)output_tensors.update(passthrough_tensors)quantized_layers.extend(passthrough_layers)- raw_tensors = _dequant_fp8_tensors(raw_tensors, block_size=fp8_block_size)+ raw_tensors = _dequant_fp8_tensors(+ raw_tensors,+ block_size=fp8_block_size,+ device=device,+ shard_name=shard_name,+ )raw_tensors.update(preserved_tensors)for tensor_name in list(raw_tensors.keys()):@@ -1097,9 +1180,17 @@ def _build_quantization_config(if differs:extra_config[layer_name] = {k: cfg.get(k) for k in scheme_keys if cfg.get(k) is not None}+ # Filter out non-Linear ops (embed, conv) that don't need to be recorded in config.+ # Routing gates and other predefined patterns are still recorded.+ non_linear_ops = ["embed", "conv"]+ non_linear_re = re.compile("|".join(re.escape(op) for op in non_linear_ops))+unique_ignored = list(dict.fromkeys(ignored_layers))for layer_name in unique_ignored:if layer_name not in extra_config:+ # Skip non-Linear ops (embed, conv) since they're not Linear layers+ if non_linear_re.search(layer_name):+ continueextra_config[layer_name] = {"bits": 16, "data_type": "float"}quantized_layer_set = set(quantized_layers)@@ -1180,6 +1271,97 @@ def _prefetch_shard(return None+def _process_single_shard_task(+ shard_idx: int,+ shard_name: str,+ *,+ model_name_or_path: str,+ work_dir: str,+ source_dir: str,+ is_streaming: bool,+ device: str,+ default_scheme: dict,+ layer_config: dict,+ ignore_patterns: list[str],+ fp8_block_size: list | None,+ model_type: str | None,+ quant_output_dir: str,+ total_shards: int,+) -> tuple[int, str, str | None, str | None, list[str] | None, list[str] | None, list[str] | None]:+ """Process one shard in an isolated subprocess task.++ Each worker builds its own matcher/cache via ``_process_shard`` to avoid+ cross-shard shared state.+ """+ shard_path = _prefetch_shard(+ model_name_or_path,+ shard_name,+ work_dir,+ source_dir,+ is_streaming,+ )+ if shard_path is None or not os.path.exists(shard_path):+ return shard_idx, shard_name, None, None, None, None, None++ output_tensors, quantized, ignored = _process_shard(+ shard_path=shard_path,+ shard_name=shard_name,+ default_scheme=default_scheme,+ layer_config=layer_config,+ ignore_patterns=ignore_patterns,+ device=device,+ fp8_block_size=fp8_block_size,+ model_type=model_type,+ )++ out_shard_name = f"model-{shard_idx + 1:05d}-of-{total_shards:05d}.safetensors"+ local_weight_map: dict[str, str] = {}+ _write_output_shard(+ quant_output_dir,+ out_shard_name,+ output_tensors,+ local_weight_map,+ )+ tensor_names = list(local_weight_map.keys())+ clear_memory()++ if is_streaming:+ try:+ os.remove(shard_path)+ except OSError:+ pass++ # Return only lightweight metadata to avoid IPC transfer of tensor storages.+ return shard_idx, shard_name, shard_path, out_shard_name, tensor_names, quantized, ignored+++def _force_cleanup_process_pool(pool: ProcessPoolExecutor | None) -> None:+ """Best-effort cleanup for process-pool workers.++ On interruption (Ctrl+C / SIGTERM) or executor failures, worker processes+ may survive briefly. This helper force-terminates workers before shutting+ the executor down.+ """+ if pool is None:+ return++ # Accessing _processes is intentionally best-effort for robust cleanup.+ # pylint: disable=protected-access+ processes = getattr(pool, "_processes", None)+ if isinstance(processes, dict):+ for proc in processes.values():+ if proc is not None and proc.is_alive():+ try:+ proc.terminate()+ except Exception:+ pass++ try:+ pool.shutdown(wait=False, cancel_futures=True)+ except Exception:+ pass++# ---------------------------------------------------------------------------# Scheme validation# ---------------------------------------------------------------------------@@ -1380,7 +1562,6 @@ class _ModelFreeCompressorCore:self.default_scheme: dict = {}self.layer_config: dict = {}self.ignore_patterns: list[str] = []- self.matcher: _PatternMatcher | None = Noneself.config: dict = {}self.fp8_block_size: list | None = Noneself.model_type: str = ""@@ -1393,6 +1574,7 @@ class _ModelFreeCompressorCore:self.all_quantized_layers: list[str] = []self.all_ignored_layers: list[str] = []self.output_weight_map: dict[str, str] = {}+ self.shard_parallelism: int = 1# -------------------------------------------------------------------# Validation / parsing@@ -1547,7 +1729,7 @@ class _ModelFreeCompressorCore:f"These layers have been automatically added to ignore_layers "f"and will be kept in full precision.\n"f"To override, pass --ignore_layers explicitly or disable "- f"model-free mode (remove --model_free)."+ f"model-free mode (--disable_model_free).")except Exception as exc:@@ -1590,12 +1772,26 @@ class _ModelFreeCompressorCore:search_dir = self.work_dir if self.is_streaming else self.source_dirself.shard_names = _list_weight_shards(search_dir)- def _build_matcher(self) -> None:- self.matcher = _PatternMatcher(- self.ignore_patterns,- self.layer_config,- self.default_scheme,- )+ def _resolve_shard_parallelism(self) -> tuple[int, str]:+ shard_count = len(self.shard_names)+ # Auto policy: shard_count // 4, capped at 10, minimum 1.+ default_parallelism = max(1, min(shard_count // 4, 10))+ env_name = "AR_MODEL_FREE_SHARD_PARALLELISM"+ if not envs.is_set(env_name):+ return min(default_parallelism, shard_count or 1), f"auto(default={default_parallelism})"++ try:+ configured = envs.AR_MODEL_FREE_SHARD_PARALLELISM+ except ValueError as e:+ logger.warning(f"{e}; using auto default {default_parallelism}.")+ raw_value = os.environ.get(env_name, "")+ return min(default_parallelism, shard_count or 1), f"invalid({raw_value!r})"++ if configured is None:+ return min(default_parallelism, shard_count or 1), f"auto(default={default_parallelism})"++ effective = min(configured, shard_count or 1)+ return effective, f"env={configured}"@propertydef _quant_output_dir(self) -> str:@@ -1619,100 +1815,83 @@ class _ModelFreeCompressorCore:except ImportError:_tqdm = None- prefetch_pool = ThreadPoolExecutor(max_workers=1)- write_pool = ThreadPoolExecutor(max_workers=1)- prefetch_future = None- write_future = None-- if self.shard_names:- prefetch_future = prefetch_pool.submit(- _prefetch_shard,- self.model_name_or_path,- self.shard_names[0],- self.work_dir,- self.source_dir,- self.is_streaming,- )+ if not self.shard_names:+ return- shard_iter = (- _tqdm(- enumerate(self.shard_names),- total=len(self.shard_names),- desc="Processing shards",- unit="shard",- )- if _tqdm- else enumerate(self.shard_names)- )+ os.makedirs(self._quant_output_dir, exist_ok=True)- for shard_idx, shard_name in shard_iter:- shard_path = prefetch_future.result() if prefetch_future else None-- # Kick off prefetch of the next shard.- if shard_idx + 1 < len(self.shard_names):- prefetch_future = prefetch_pool.submit(- _prefetch_shard,- self.model_name_or_path,- self.shard_names[shard_idx + 1],- self.work_dir,- self.source_dir,- self.is_streaming,+ worker_count = max(1, min(self.shard_parallelism, len(self.shard_names)))+ futures = []+ pool: ProcessPoolExecutor | None = None+ try:+ pool = ProcessPoolExecutor(max_workers=worker_count, mp_context=mp.get_context("spawn"))+ for shard_idx, shard_name in enumerate(self.shard_names):+ futures.append(+ pool.submit(+ _process_single_shard_task,+ shard_idx,+ shard_name,+ model_name_or_path=self.model_name_or_path,+ work_dir=self.work_dir,+ source_dir=self.source_dir,+ is_streaming=self.is_streaming,+ device=self.device,+ default_scheme=self.default_scheme,+ layer_config=self.layer_config,+ ignore_patterns=self.ignore_patterns,+ fp8_block_size=self.fp8_block_size,+ model_type=self.model_type,+ quant_output_dir=self._quant_output_dir,+ total_shards=len(self.shard_names),+ ))- else:- prefetch_future = None- if shard_path is None or not os.path.exists(shard_path):- logger.warning(f"Shard not found: {shard_name}, skipping")- continue-- output_tensors, quantized, ignored = _process_shard(- shard_path=shard_path,- device=self.device,- matcher=self.matcher,- fp8_block_size=self.fp8_block_size,- model_type=self.model_type,- )- memory_monitor.update()- clear_memory()- if len(self.shard_names) > 1:- logger.info(f"Memory usage: {memory_monitor.get_summary()}")-- # Log per-shard summary- compressed_quantized = compress_layer_names(quantized)- compressed_ignored = compress_layer_names(ignored)- logger.info(- f"Shard {shard_idx + 1}/{len(self.shard_names)} ({shard_name}):\n"- f" Quantized layers ({len(quantized)}): {compressed_quantized}\n"- f" Ignored layers ({len(ignored)}): {compressed_ignored}"+ shard_iter = (+ _tqdm(as_completed(futures), total=len(futures), desc="Processing shards", unit="shard")+ if _tqdm+ else as_completed(futures))- self.all_quantized_layers.extend(quantized)- self.all_ignored_layers.extend(ignored)-- if write_future is not None:- write_future.result()-- os.makedirs(self._quant_output_dir, exist_ok=True)- out_shard_name = f"model-{shard_idx + 1:05d}-of-{len(self.shard_names):05d}.safetensors"- write_future = write_pool.submit(- _write_output_shard,- self._quant_output_dir,- out_shard_name,- output_tensors,- self.output_weight_map,- )-- if self.is_streaming:- try:- os.remove(shard_path)- logger.debug(f"Deleted source shard: {shard_path}")- except OSError as e:- logger.warning(f"Could not delete source shard {shard_path}: {e}")+ for future in shard_iter:+ shard_idx, shard_name, shard_path, out_shard_name, tensor_names, quantized, ignored = future.result()++ if (+ shard_path is None+ or out_shard_name is None+ or tensor_names is None+ or quantized is None+ or ignored is None+ ):+ logger.warning(f"Shard not found: {shard_name}, skipping")+ continue++ memory_monitor.update()+ clear_memory()+ if len(self.shard_names) > 1:+ logger.info(f"Memory usage: {memory_monitor.get_summary()}")++ compressed_quantized = compress_layer_names(quantized)+ compressed_ignored = compress_layer_names(ignored)+ logger.info(+ f"Shard {shard_idx + 1}/{len(self.shard_names)} ({shard_name}):\n"+ f" Quantized layers ({len(quantized)}): {compressed_quantized}\n"+ f" Ignored layers ({len(ignored)}): {compressed_ignored}"+ )- prefetch_pool.shutdown(wait=False)- if write_future is not None:- write_future.result()- write_pool.shutdown(wait=True)+ self.all_quantized_layers.extend(quantized)+ self.all_ignored_layers.extend(ignored)++ for tensor_name in tensor_names:+ self.output_weight_map[tensor_name] = out_shard_name+ except KeyboardInterrupt:+ logger.warning("Interrupted by user; terminating model-free shard worker processes.")+ _force_cleanup_process_pool(pool)+ raise+ except Exception:+ _force_cleanup_process_pool(pool)+ raise+ finally:+ _force_cleanup_process_pool(pool)# -------------------------------------------------------------------# Output@@ -1806,10 +1985,10 @@ class _ModelFreeCompressorCore:self._resolve_source()self._check_conv1d_and_embedding()self._apply_predefined_ignore_layers()- self._build_matcher()self._detect_fp8_source()self._resolve_model_type()self._discover_shards()+ self.shard_parallelism, shard_parallelism_source = self._resolve_shard_parallelism()# Determine the output packing format based on scheme data typedata_type = (self.default_scheme.get("data_type") or "int").lower()@@ -1825,6 +2004,8 @@ class _ModelFreeCompressorCore:f" Packing format: {packing_format}\n"f" Output: {self.output_dir}\n"f" Shards: {len(self.shard_names)}\n"+ f" Shard parallelism: {self.shard_parallelism} ({shard_parallelism_source}, "+ f"env AR_MODEL_FREE_SHARD_PARALLELISM)\n"f" Streaming download: {self.is_streaming}\n"f" Diffusion model: {self.is_diffusion_model}\n"f" Quant lm_head: {self.quant_lm_head}\n"diff --git a/auto_round/envs.py b/auto_round/envs.pyindex fe258bc4c..a6df79435 100644--- a/auto_round/envs.py+++ b/auto_round/envs.py@@ -20,10 +20,26 @@ from typing import TYPE_CHECKING, Any, Callable, Optionalif TYPE_CHECKING:AR_LOG_LEVEL: str = "INFO"AR_USE_MODELSCOPE: bool = "False"+ AR_MODEL_FREE_SHARD_PARALLELISM: Optional[int] = NoneAUTO_ROUND_CACHE: Optional[str] = NoneAUTO_ROUND_GGUF_AUTO_UPDATE: bool = FalseLLAMA_CPP_ROOT: Optional[str] = None++def _get_optional_positive_int_env(name: str) -> Optional[int]:+ """Read an optional env var that must be a positive integer when set."""+ raw = os.getenv(name)+ if raw is None:+ return None+ try:+ value = int(raw)+ except ValueError as exc:+ raise ValueError(f"{name} must be a positive integer, got {raw!r}") from exc+ if value < 1:+ raise ValueError(f"{name} must be a positive integer, got {value}")+ return value++environment_variables: dict[str, Callable[[], Any]] = {# this is used for configuring the default logging level"AR_LOG_LEVEL": lambda: os.getenv("AR_LOG_LEVEL", "INFO").upper(),@@ -54,6 +70,7 @@ environment_variables: dict[str, Callable[[], Any]] = {# o_proj, gate/up/down_proj, ...) so that per-layer static recompiles do# not exceed dynamo's default limit (8) and fall back to eager."AR_DYNAMO_CACHE_SIZE_LIMIT": lambda: int(os.getenv("AR_DYNAMO_CACHE_SIZE_LIMIT", "16")),+ "AR_MODEL_FREE_SHARD_PARALLELISM": lambda: _get_optional_positive_int_env("AR_MODEL_FREE_SHARD_PARALLELISM"),"AUTO_ROUND_CACHE": lambda: os.getenv("AUTO_ROUND_CACHE", None),"AUTO_ROUND_GGUF_AUTO_UPDATE": lambda: os.getenv("AUTO_ROUND_GGUF_AUTO_UPDATE", "0").lower()in ("1", "true", "yes", "on"),diff --git a/docs/environments.md b/docs/environments.mdindex e232e8831..89d9bf100 100644--- a/docs/environments.md+++ b/docs/environments.md@@ -109,6 +109,18 @@ export AR_SEARCH_SCALE_RATIO=0.75export AR_DYNAMO_CACHE_SIZE_LIMIT=32```+### AR_MODEL_FREE_SHARD_PARALLELISM+- **Description**: Controls how many weight shards are processed concurrently during model-free quantization. Increasing this value improves resource utilization but consumes more RAM.+ - Auto policy (when the variable is **not** set): `shard_count // 4`, capped at **10**, minimum **1**. For example, 8 shards → 2 workers; 40 shards → 10 workers.+ - The effective parallelism is always capped to the actual number of shards.+- **Default**: unset → auto policy applies (`shard_count // 4`, max 10, min 1)+- **Valid Values**: any positive integer; these are not restricted to specific values — e.g. `2`, `4`, `6`, `8`+- **Usage**: Set this to override the automatic parallelism selection++```bash+export AR_MODEL_FREE_SHARD_PARALLELISM=4+```+## Usage Examples### Setting Environment Variablesdiff --git a/docs/environments_CN.md b/docs/environments_CN.mdindex 9525de3a1..606f6b1f3 100644--- a/docs/environments_CN.md+++ b/docs/environments_CN.md@@ -109,6 +109,18 @@ export AR_SEARCH_SCALE_RATIO=0.75export AR_DYNAMO_CACHE_SIZE_LIMIT=32```+### AR_MODEL_FREE_SHARD_PARALLELISM+- **描述**:控制 model-free 量化时同时处理的权重 shard 数量。增大该值可提高资源利用率,但会占用更多内存。+ - 自动策略(变量**未设置**时):`shard_count // 4`,最大 **10**,最小 **1**。例如:8 个 shard → 2 个 worker;40 个 shard → 10 个 worker。+ - 实际并行数始终不超过 shard 总数。+- **默认值**:未设置 → 走自动策略(`shard_count // 4`,最大 10,最小 1)+- **有效值**:任意正整数,不限于特定值,如 `2`、`4`、`6`、`8`;不能整除 shard 数时会自动均匀分配,末批处理剩余 shard,结果正确+- **用途**:覆盖自动并行策略,手动指定并行数++```bash+export AR_MODEL_FREE_SHARD_PARALLELISM=4+```+## 使用示例### 设置环境变量diff --git a/docs/step_by_step.md b/docs/step_by_step.mdindex ff757ac41..d1eb3d013 100644--- a/docs/step_by_step.md+++ b/docs/step_by_step.md@@ -568,6 +568,40 @@ Model-free mode performs RTN WOQ quantization **without loading the full model i- **Predefined ignore layers** – automatically skips model-specific layers (e.g., MoE gates, MTP layers) based on config detection- **Bit-exact parity** with the standard `--iters 0 --disable_opt_rtn` flow for all supported schemes+<details>+ <summary>Model-free Parallelism Benchmarks (Rounded Minutes)</summary>++Runtime normalization: all `mm:ss` values are rounded up to the next full minute. For example, `4:20 -> 5`, `15:45 -> 16`, `9:07 -> 10`, `7:29 -> 8`, `4:09 -> 5`.++| Model | Device | Scheme | Parallelism | Peak Memory (G) | Runtime (min, rounded up) |+|---|---|---|---:|---:|---:|+| Qwen/Qwen3-Next-80B-A3B-Instruct | A100 | W4A16 | 1 | 2 | N/A |+| Qwen/Qwen3-Next-80B-A3B-Instruct | A100 | W4A16 | 10 | 8 | 7 |+| Qwen3-235B-A22B-Instruct-2507 | A100 | W4A16 | 1 | 2 | 17 |+| Qwen3-235B-A22B-Instruct-2507 | A100 | W4A16 | 10 | 8 | 5 |+| zai-org/GLM-5.2 | B200 | MXFP4-Mixed | 1 | 2 | 60 |+| zai-org/GLM-5.2 | B200 | MXFP4-Mixed | 10 | 27 | 16 |+| zai-org/GLM-5.2 | B200 | W4A16 | 1 | 3 | 30 |+| zai-org/GLM-5.2 | B200 | W4A16 | 10 | 16 | 10 |+| zai-org/GLM-5.2 | B200 | W4A16 | 20 | 32 | 8 |+| MiniMaxAI/MiniMax-M2.7 (FP8) | B200 | W4A16 | 1 | 2 | 18 |+| MiniMaxAI/MiniMax-M2.7 (FP8) | B200 | W4A16 | 10 | 10 | 5 |+| deepseek-ai/DeepSeek-V4-Pro (MXFP) | B200 | W4A16 | 1 | 6 | 80 |+| deepseek-ai/DeepSeek-V4-Pro (MXFP) | B200 | W4A16 | 10 | 50 | 13 |++| Model | Scheme | Comparison | Runtime Change (min) | Speedup | Time Saved | Peak Memory Change |+|---|---|---|---|---:|---:|---|+| Qwen3-235B | W4A16 | Parallelism 1 -> 10 | 17 -> 5 | 3.40x | 70.6% | 2G -> 8G |+| GLM-5.2 | MXFP4-Mixed | Parallelism 1 -> 10 | 60 -> 16 | 3.75x | 73.3% | 2G -> 27G |+| GLM-5.2 | W4A16 | Parallelism 1 -> 10 | 30 -> 10 | 3.00x | 66.7% | 3G -> 16G |+| GLM-5.2 | W4A16 | Parallelism 1 -> 20 | 30 -> 8 | 3.75x | 73.3% | 3G -> 32G |+| MiniMax-M2.7 | W4A16 | Parallelism 1 -> 10 | 18 -> 5 | 3.60x | 72.2% | 2G -> 10G |+| DeepSeek-V4-Pro | W4A16 | Parallelism 1 -> 10 | 80 -> 13 | 6.15x | 83.8% | 6G -> 50G |++Key takeaway: model-free quantization usually gets about `3x-6x` runtime speedup with higher parallelism, while peak memory usage increases significantly.++</details>+<details><summary>Click to expand supported schemes and examples</summary>diff --git a/docs/step_by_step_CN.md b/docs/step_by_step_CN.mdindex c646ab672..057f68563 100644--- a/docs/step_by_step_CN.md+++ b/docs/step_by_step_CN.md@@ -566,6 +566,40 @@ ar.quantize_and_save(output_dir, format="auto_round")- **预定义忽略层** — 根据模型配置自动跳过特定层(如 MoE 门控层、MTP 层等)- 与标准 `--iters 0 --disable_opt_rtn` 流程对所有受支持的 scheme **位级等价**+<details>+ <summary>Model-free 并行量化基准(分钟向上取整)</summary>++时间归一化规则:所有 `mm:ss` 均向上取整到分钟。例如:`4:20 -> 5`、`15:45 -> 16`、`9:07 -> 10`、`7:29 -> 8`、`4:09 -> 5`。++| 模型 | 设备 | 方案 | 并行度 | 峰值显存 (G) | 耗时(分钟,向上取整) |+|---|---|---|---:|---:|---:|+| Qwen/Qwen3-Next-80B-A3B-Instruct | A100 | W4A16 | 1 | 2 | N/A |+| Qwen/Qwen3-Next-80B-A3B-Instruct | A100 | W4A16 | 10 | 8 | 7 |+| Qwen3-235B-A22B-Instruct-2507 | A100 | W4A16 | 1 | 2 | 17 |+| Qwen3-235B-A22B-Instruct-2507 | A100 | W4A16 | 10 | 8 | 5 |+| zai-org/GLM-5.2 | B200 | MXFP4-Mixed | 1 | 2 | 60 |+| zai-org/GLM-5.2 | B200 | MXFP4-Mixed | 10 | 27 | 16 |+| zai-org/GLM-5.2 | B200 | W4A16 | 1 | 3 | 30 |+| zai-org/GLM-5.2 | B200 | W4A16 | 10 | 16 | 10 |+| zai-org/GLM-5.2 | B200 | W4A16 | 20 | 32 | 8 |+| MiniMaxAI/MiniMax-M2.7 (FP8) | B200 | W4A16 | 1 | 2 | 18 |+| MiniMaxAI/MiniMax-M2.7 (FP8) | B200 | W4A16 | 10 | 10 | 5 |+| deepseek-ai/DeepSeek-V4-Pro (MXFP) | B200 | W4A16 | 1 | 6 | 80 |+| deepseek-ai/DeepSeek-V4-Pro (MXFP) | B200 | W4A16 | 10 | 50 | 13 |++| 模型 | 方案 | 对比 | 耗时变化(分钟) | 加速比 | 时间节省 | 峰值显存变化 |+|---|---|---|---|---:|---:|---|+| Qwen3-235B | W4A16 | 并行 1 -> 10 | 17 -> 5 | 3.40x | 70.6% | 2G -> 8G |+| GLM-5.2 | MXFP4-Mixed | 并行 1 -> 10 | 60 -> 16 | 3.75x | 73.3% | 2G -> 27G |+| GLM-5.2 | W4A16 | 并行 1 -> 10 | 30 -> 10 | 3.00x | 66.7% | 3G -> 16G |+| GLM-5.2 | W4A16 | 并行 1 -> 20 | 30 -> 8 | 3.75x | 73.3% | 3G -> 32G |+| MiniMax-M2.7 | W4A16 | 并行 1 -> 10 | 18 -> 5 | 3.60x | 72.2% | 2G -> 10G |+| DeepSeek-V4-Pro | W4A16 | 并行 1 -> 10 | 80 -> 13 | 6.15x | 83.8% | 6G -> 50G |++结论:在 model-free 量化中,提高并行度通常可带来约 `3x-6x` 的耗时加速,但峰值显存会明显上升。++</details>+<details><summary>点击展开支持的 Scheme 与示例</summary>diff --git a/test/test_cpu/quantization/test_model_free.py b/test/test_cpu/quantization/test_model_free.pyindex df73b9363..1c011bd60 100644--- a/test/test_cpu/quantization/test_model_free.py+++ b/test/test_cpu/quantization/test_model_free.py@@ -25,6 +25,7 @@ from safetensors.torch import save_filefrom auto_round import AutoRoundfrom auto_round.compressors.model_free import (_build_mxfp_quantization_config,+ _build_quantization_config,_dequant_fp8_tensors,_dequant_mxfp_tensors,_expand_e8m0_block_scale,@@ -329,6 +330,38 @@ class TestFP8Source:assert "layer" in quantized+# ===========================================================================+# Quantization config builder+# ===========================================================================+++class TestBuildQuantizationConfig:+ def test_extra_config_filters_embed_conv_only(self):+ default = {"bits": 4, "group_size": 128, "sym": True, "data_type": "int"}+ ignored = [+ "model.embed_tokens",+ "model.conv1",+ "model.layers.0.shared_expert_gate",+ "model.layers.0.mlp.gate",+ ]++ cfg = _build_quantization_config(+ default_scheme=default,+ layer_config={},+ ignore_patterns=[],+ quantized_layers=[],+ ignored_layers=ignored,+ )++ extra = cfg.get("extra_config", {})+ # Non-Linear ops are filtered out.+ assert "model.embed_tokens" not in extra+ assert "model.conv1" not in extra+ # Other ignored layers should still be recorded.+ assert extra["model.layers.0.shared_expert_gate"] == {"bits": 16, "data_type": "float"}+ assert extra["model.layers.0.mlp.gate"] == {"bits": 16, "data_type": "float"}++# ===========================================================================# End-to-end ModelFreeQuantize# ===========================================================================@@ -1163,3 +1196,111 @@ class TestCopyMetadataSubfolders:assert any(k.endswith(".qweight") for k in keys), f"Quantized transformer should contain .qweight tensors, got: {keys}"+++# ===========================================================================+# Shard parallelism — _resolve_shard_parallelism + end-to-end with non-divisible counts+# ===========================================================================+++class TestResolveShardParallelism:+ """Tests for the automatic and env-controlled shard parallelism policy."""++ @staticmethod+ def _core_with_n_shards(n: int) -> _ModelFreeCompressorCore:+ core = _ModelFreeCompressorCore.__new__(_ModelFreeCompressorCore)+ core.shard_names = [f"shard_{i:02d}.safetensors" for i in range(n)]+ core.shard_parallelism = 1+ return core++ def test_auto_policy_formula(self, monkeypatch):+ monkeypatch.delenv("AR_MODEL_FREE_SHARD_PARALLELISM", raising=False)+ cases = [+ (1, 1), # 1 // 4 = 0 -> min 1+ (3, 1), # 3 // 4 = 0 -> min 1+ (4, 1), # 4 // 4 = 1+ (8, 2), # 8 // 4 = 2+ (12, 3), # 12 // 4 = 3+ (40, 10), # 40 // 4 = 10 (at cap)+ (80, 10), # 80 // 4 = 20 -> capped at 10+ ]+ for n, expected in cases:+ core = self._core_with_n_shards(n)+ p, src = core._resolve_shard_parallelism()+ assert p == expected, f"n={n}: expected {expected}, got {p}"+ assert "auto" in src++ def test_env_override_respected(self, monkeypatch):+ monkeypatch.setenv("AR_MODEL_FREE_SHARD_PARALLELISM", "7")+ core = self._core_with_n_shards(25)+ p, src = core._resolve_shard_parallelism()+ assert p == 7+ assert "env=7" in src++ def test_env_capped_at_shard_count(self, monkeypatch):+ monkeypatch.setenv("AR_MODEL_FREE_SHARD_PARALLELISM", "100")+ core = self._core_with_n_shards(3)+ p, _ = core._resolve_shard_parallelism()+ assert p == 3++ def test_env_below_1_falls_back_to_auto(self, monkeypatch):+ monkeypatch.setenv("AR_MODEL_FREE_SHARD_PARALLELISM", "0")+ core = self._core_with_n_shards(25)+ p, src = core._resolve_shard_parallelism()+ assert p == 25 // 4+ assert "invalid" in src++ def test_env_invalid_falls_back_to_auto(self, monkeypatch):+ monkeypatch.setenv("AR_MODEL_FREE_SHARD_PARALLELISM", "notanumber")+ core = self._core_with_n_shards(25)+ p, src = core._resolve_shard_parallelism()+ assert p == 25 // 4 # auto formula: shard_count // 4+ assert "invalid" in src++ def test_nondivisible_shard_count_all_shards_processed(self, tmp_path, monkeypatch):+ """Parallelism that does not evenly divide the shard count must still+ process every shard and produce correct output.++ 7 shards with parallelism=3 → 7 % 3 == 1 (non-divisible).+ """+ monkeypatch.setenv("AR_MODEL_FREE_SHARD_PARALLELISM", "3")++ # Build 7 shards of simple linear weights+ layer_names = [f"model.layers.{i}.fc.weight" for i in range(7)]+ model_dir = str(tmp_path / "source")+ os.makedirs(model_dir, exist_ok=True)+ with open(os.path.join(model_dir, "config.json"), "w") as f:+ json.dump(_SIMPLE_CONFIG, f)++ weight_map = {}+ for shard_idx, layer_name in enumerate(layer_names):+ shard_filename = f"model-{shard_idx + 1:05d}-of-{len(layer_names):05d}.safetensors"+ save_file({layer_name: torch.randn(128, 128)}, os.path.join(model_dir, shard_filename))+ weight_map[layer_name] = shard_filename+ with open(os.path.join(model_dir, "model.safetensors.index.json"), "w") as f:+ json.dump({"metadata": {"total_size": 0}, "weight_map": weight_map}, f)++ output_dir = str(tmp_path / "output")+ core = _ModelFreeCompressorCore(+ model_name_or_path=model_dir,+ output_dir=output_dir,+ scheme="W4A16",+ quant_lm_head=True,+ )+ core.run()++ # Every layer must appear as quantized in the output+ out_keys = _read_output_keys(output_dir)+ for layer_name in layer_names:+ base = layer_name.replace(".weight", "")+ assert f"{base}.qweight" in out_keys, (+ f"Layer '{base}' missing from output after non-divisible shard processing. "+ f"Output keys: {sorted(out_keys)[:20]}"+ )++ # The index must reference exactly 7 shards+ index_path = os.path.join(output_dir, "model.safetensors.index.json")+ with open(index_path) as f:+ index = json.load(f)+ unique_shards = set(index["weight_map"].values())+ assert len(unique_shards) == 7, f"Expected 7 output shards, got {len(unique_shards)}: {unique_shards}"