VideoCoT-RoboTwin / code /openpi /models /w8_checkpoint.py
IsaacZhy's picture
Upload inference-only Video-CoT RoboTwin stage2 40K checkpoint and loader
1acbcb7 verified
Raw History Blame Contribute Delete
8.93 kB
"""Utilities for W8 checkpoint storage with dequant-on-load.
This format stores selected large weights as int8 plus group-wise fp16 scales.
At runtime we dequantize them back to bf16/float before constructing the normal
model, so existing model forward code does not need quantized matmul support.
"""
from __future__ import annotations
from collections.abc import Iterable
import json
import pathlib
from typing import Any
from flax import traverse_util
import jax
import jax.numpy as jnp
import numpy as np
import orbax.checkpoint as ocp
from openpi.shared import array_typing as at
FORMAT_VERSION = 1
def path_str(path: Iterable[Any]) -> str:
return "/".join(str(p) for p in path)
def component_for_path(path: str) -> str:
if "/img/" in f"/{path}/" or path.startswith("PaliGemma/img"):
return "vision_siglip"
if "PaliGemma/llm" in path:
if "_1/" in path or path.endswith("_1"):
return "coarse_expert"
if "_2/" in path or path.endswith("_2"):
return "fine_expert"
if "embedder" in path or "input_embedding" in path:
return "llm_embedding"
return "llm_backbone"
if "implicit_action_reasoner" in path:
return "iar"
if "explicit_action_reasoner" in path:
return "ear_fusion"
if "action_reason" in path or "action_time" in path or "action_in_proj" in path or "action_out_proj" in path:
return "action_io_fusion"
if "time_mlp" in path or "state_proj" in path:
return "action_io_fusion"
if "video" in path or "horizon" in path or "pixel" in path:
return "video_cot"
return "other"
def tensor_kind(path: str, arr: np.ndarray) -> str:
leaf = path.rsplit("/", 1)[-1]
if leaf in {"bias", "scale"} or arr.ndim <= 1:
return "norm_bias_small"
if "input_embedding" in path:
return "embedding"
if leaf in {"kernel", "w", "gating_einsum", "linear"}:
return "matmul_weight"
if arr.ndim >= 2:
return "other_matrix"
return "other"
def should_quantize(component: str, kind: str, policy: str) -> bool:
if kind not in {"matmul_weight", "embedding", "other_matrix"}:
return False
if policy == "llm_only":
return component in {"llm_backbone", "llm_embedding"}
if policy == "llm_experts":
return component in {"llm_backbone", "llm_embedding", "coarse_expert", "fine_expert"}
if policy == "experts_only":
return component in {"coarse_expert", "fine_expert"}
if policy == "all_large":
return component not in {"norm_bias_small", "other"}
raise ValueError(f"unknown quantization policy: {policy}")
def quantize_w8_array(
arr: np.ndarray,
*,
group_size: int,
chunk_groups: int,
) -> tuple[np.ndarray, np.ndarray]:
"""Symmetric group-wise int8 quantization."""
flat_src = np.asarray(arr, dtype=np.float32).reshape(-1)
q_out = np.empty(flat_src.shape, dtype=np.int8)
n_groups = (flat_src.size + group_size - 1) // group_size
scales_out = np.empty((n_groups,), dtype=np.float16)
chunk_elems = max(group_size, group_size * chunk_groups)
group_offset = 0
for start in range(0, flat_src.size, chunk_elems):
end = min(start + chunk_elems, flat_src.size)
chunk = flat_src[start:end]
pad = (-chunk.size) % group_size
chunk_work = np.pad(chunk, (0, pad), mode="constant") if pad else chunk
grouped = chunk_work.reshape(-1, group_size)
scales = np.max(np.abs(grouped), axis=1) / 127.0
scales = np.where(np.isfinite(scales) & (scales > 0), scales, 1.0).astype(np.float32)
q = np.clip(np.round(grouped / scales[:, None]), -127, 127).astype(np.int8)
q_out[start:end] = q.reshape(-1)[: chunk.size]
scales_out[group_offset : group_offset + scales.shape[0]] = scales.astype(np.float16)
group_offset += scales.shape[0]
return q_out.reshape(arr.shape), scales_out
def dequantize_w8_array(
q: np.ndarray,
scales: np.ndarray,
*,
group_size: int,
dtype: jnp.dtype,
chunk_groups: int = 65536,
) -> jax.Array:
flat_q = np.asarray(q, dtype=np.int8).reshape(-1)
scales = np.asarray(scales, dtype=np.float32).reshape(-1)
out = np.empty(flat_q.shape, dtype=np.float32)
chunk_elems = max(group_size, group_size * chunk_groups)
for start in range(0, flat_q.size, chunk_elems):
end = min(start + chunk_elems, flat_q.size)
group_start = start // group_size
group_end = (end + group_size - 1) // group_size
chunk = flat_q[start:end].astype(np.float32)
pad = (-chunk.size) % group_size
chunk_work = np.pad(chunk, (0, pad), mode="constant") if pad else chunk
grouped = chunk_work.reshape(-1, group_size)
deq = grouped * scales[group_start:group_end, None]
out[start:end] = deq.reshape(-1)[: chunk.size]
return jnp.asarray(out.reshape(q.shape), dtype=dtype)
def save_w8_checkpoint(
params: at.Params,
output_dir: pathlib.Path | str,
*,
policy: str,
group_size: int = 128,
chunk_groups: int = 65536,
) -> dict[str, Any]:
"""Save a W8 params directory and return summary metadata."""
output_dir = pathlib.Path(output_dir)
flat = traverse_util.flatten_dict(params, sep=None)
q_flat: dict[tuple[Any, ...], np.ndarray] = {}
scale_flat: dict[tuple[Any, ...], np.ndarray] = {}
float_flat: dict[tuple[Any, ...], np.ndarray] = {}
quantized_keys: list[str] = []
quantized_params = 0
total_params = 0
for key, value in flat.items():
if not isinstance(value, np.ndarray):
value = np.asarray(value)
total_params += int(value.size)
path = path_str(key)
component = component_for_path(path)
kind = tensor_kind(path, value)
if should_quantize(component, kind, policy):
q, scales = quantize_w8_array(value, group_size=group_size, chunk_groups=chunk_groups)
q_flat[key] = q
scale_flat[key] = scales
quantized_keys.append(path)
quantized_params += int(value.size)
else:
float_flat[key] = value
payload = {
"qparams": traverse_util.unflatten_dict(q_flat, sep=None),
"scales": traverse_util.unflatten_dict(scale_flat, sep=None),
"float_params": traverse_util.unflatten_dict(float_flat, sep=None),
}
with ocp.PyTreeCheckpointer() as ckptr:
ckptr.save(output_dir, payload)
manifest = {
"format": "openpi_w8_dequant_on_load",
"format_version": FORMAT_VERSION,
"bits": 8,
"policy": policy,
"group_size": group_size,
"quantized_params": quantized_params,
"total_params": total_params,
"quantized_fraction": quantized_params / total_params if total_params else 0.0,
"quantized_keys": quantized_keys,
}
(output_dir / "w8_manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True))
return manifest
def restore_w8_params(
w8_params_path: pathlib.Path | str,
*,
dtype: jnp.dtype = jnp.bfloat16,
chunk_groups: int = 65536,
) -> at.Params:
"""Restore W8 params and dequantize selected tensors to `dtype`."""
w8_params_path = pathlib.Path(w8_params_path).resolve()
manifest_path = w8_params_path / "w8_manifest.json"
if not manifest_path.exists():
raise FileNotFoundError(f"W8 manifest not found at: {manifest_path}")
manifest = json.loads(manifest_path.read_text())
if manifest.get("format_version") != FORMAT_VERSION:
raise ValueError(f"Unsupported W8 checkpoint version: {manifest.get('format_version')}")
group_size = int(manifest["group_size"])
with ocp.PyTreeCheckpointer() as ckptr:
metadata = ckptr.metadata(w8_params_path)
item = {name: metadata[name] for name in ("qparams", "scales", "float_params")}
restored = ckptr.restore(
w8_params_path,
ocp.args.PyTreeRestore(
item=item,
restore_args=jax.tree.map(lambda _: ocp.ArrayRestoreArgs(restore_type=np.ndarray), item),
),
)
q_flat = traverse_util.flatten_dict(restored["qparams"], sep=None)
scale_flat = traverse_util.flatten_dict(restored["scales"], sep=None)
float_flat = traverse_util.flatten_dict(restored["float_params"], sep=None)
out: dict[tuple[Any, ...], Any] = {}
for key, value in float_flat.items():
arr = np.asarray(value)
out[key] = jnp.asarray(arr, dtype=dtype) if np.issubdtype(arr.dtype, np.floating) else jnp.asarray(arr)
for key, q in q_flat.items():
out[key] = dequantize_w8_array(
np.asarray(q),
np.asarray(scale_flat[key]),
group_size=group_size,
dtype=dtype,
chunk_groups=chunk_groups,
)
return traverse_util.unflatten_dict(out, sep=None)