| """ |
| Diagnose 3DGS PLY parameter spaces and quantization artifacts. |
| |
| Use this before blaming the Transformer. It checks whether scale/opacity/rotation |
| fields look like standard 3DGS raw parameters, and optionally compares a |
| quantized/reconstructed PLY against the original PLY. |
| |
| Examples: |
| python diagnose_ply_fields.py original.ply |
| python diagnose_ply_fields.py original.ply --compare reconstructed.ply |
| """ |
|
|
| import argparse |
| import os |
|
|
| import numpy as np |
|
|
| try: |
| from plyfile import PlyData |
| except ModuleNotFoundError: |
| PlyData = None |
|
|
|
|
| PERCENTILES = [0, 1, 50, 90, 95, 99, 99.9, 100] |
|
|
| PLY_DTYPE_MAP = { |
| "char": "i1", |
| "int8": "i1", |
| "uchar": "u1", |
| "uint8": "u1", |
| "short": "i2", |
| "int16": "i2", |
| "ushort": "u2", |
| "uint16": "u2", |
| "int": "i4", |
| "int32": "i4", |
| "uint": "u4", |
| "uint32": "u4", |
| "float": "f4", |
| "float32": "f4", |
| "double": "f8", |
| "float64": "f8", |
| } |
|
|
|
|
| def sigmoid(x: np.ndarray) -> np.ndarray: |
| x = np.clip(x, -80.0, 80.0) |
| return 1.0 / (1.0 + np.exp(-x)) |
|
|
|
|
| def read_vertex_without_plyfile(ply_path: str) -> np.ndarray: |
| with open(ply_path, "rb") as f: |
| first = f.readline().decode("ascii", errors="replace").strip() |
| if first != "ply": |
| raise ValueError(f"{ply_path} is not a PLY file") |
|
|
| fmt = None |
| vertex_count = None |
| vertex_props = [] |
| current_element = None |
|
|
| while True: |
| line_b = f.readline() |
| if not line_b: |
| raise ValueError(f"{ply_path} ended before end_header") |
| line = line_b.decode("ascii", errors="replace").strip() |
| if line == "end_header": |
| data_start = f.tell() |
| break |
| if not line or line.startswith("comment"): |
| continue |
| parts = line.split() |
| if parts[0] == "format": |
| fmt = parts[1] |
| elif parts[0] == "element": |
| current_element = parts[1] |
| if current_element == "vertex": |
| vertex_count = int(parts[2]) |
| elif parts[0] == "property" and current_element == "vertex": |
| if parts[1] == "list": |
| raise ValueError("List properties inside vertex are not supported by the fallback reader.") |
| prop_type, prop_name = parts[1], parts[2] |
| if prop_type not in PLY_DTYPE_MAP: |
| raise ValueError(f"Unsupported PLY property type: {prop_type}") |
| vertex_props.append((prop_name, PLY_DTYPE_MAP[prop_type])) |
|
|
| if fmt is None or vertex_count is None: |
| raise ValueError(f"{ply_path} missing format or vertex element in header") |
| if not vertex_props: |
| raise ValueError(f"{ply_path} has no vertex properties") |
|
|
| if fmt == "binary_little_endian": |
| dtype = np.dtype(vertex_props).newbyteorder("<") |
| f.seek(data_start) |
| data = np.fromfile(f, dtype=dtype, count=vertex_count) |
| if data.shape[0] != vertex_count: |
| raise ValueError(f"Expected {vertex_count} vertices, read {data.shape[0]}") |
| return data |
|
|
| if fmt == "binary_big_endian": |
| dtype = np.dtype(vertex_props).newbyteorder(">") |
| f.seek(data_start) |
| data = np.fromfile(f, dtype=dtype, count=vertex_count) |
| if data.shape[0] != vertex_count: |
| raise ValueError(f"Expected {vertex_count} vertices, read {data.shape[0]}") |
| return data |
|
|
| if fmt == "ascii": |
| f.seek(data_start) |
| rows = [] |
| for _ in range(vertex_count): |
| line = f.readline().decode("ascii", errors="replace").strip() |
| rows.append(line.split()) |
| raw = np.asarray(rows, dtype=np.float64) |
| dtype = np.dtype(vertex_props) |
| data = np.empty(vertex_count, dtype=dtype) |
| for i, (name, _) in enumerate(vertex_props): |
| data[name] = raw[:, i].astype(data.dtype[name]) |
| return data |
|
|
| raise ValueError(f"Unsupported PLY format: {fmt}") |
|
|
|
|
| def read_vertex(ply_path: str) -> np.ndarray: |
| if PlyData is not None: |
| plydata = PlyData.read(ply_path) |
| return plydata["vertex"].data |
| return read_vertex_without_plyfile(ply_path) |
|
|
|
|
| def read_fields(ply_path: str) -> dict: |
| vertex = read_vertex(ply_path) |
| names = vertex.dtype.names |
|
|
| required = [ |
| "scale_0", |
| "scale_1", |
| "scale_2", |
| "opacity", |
| "rot_0", |
| "rot_1", |
| "rot_2", |
| "rot_3", |
| ] |
| missing = [name for name in required if name not in names] |
| if missing: |
| raise ValueError(f"{ply_path} missing fields: {missing}") |
|
|
| scale = np.stack( |
| [vertex["scale_0"], vertex["scale_1"], vertex["scale_2"]], axis=1 |
| ).astype(np.float64) |
| opacity = np.asarray(vertex["opacity"], dtype=np.float64) |
| rot = np.stack( |
| [vertex["rot_0"], vertex["rot_1"], vertex["rot_2"], vertex["rot_3"]], axis=1 |
| ).astype(np.float64) |
|
|
| xyz = None |
| if all(name in names for name in ["x", "y", "z"]): |
| xyz = np.stack([vertex["x"], vertex["y"], vertex["z"]], axis=1).astype( |
| np.float64 |
| ) |
|
|
| return { |
| "scale": scale, |
| "opacity": opacity, |
| "rot": rot, |
| "xyz": xyz, |
| "n": scale.shape[0], |
| } |
|
|
|
|
| def print_percentiles(title: str, values: np.ndarray) -> None: |
| pct = np.percentile(values, PERCENTILES, axis=0) |
| print(f"\n[{title}]") |
| for p, row in zip(PERCENTILES, pct): |
| if np.ndim(row) == 0: |
| print(f" p{p:>5}: {float(row): .8g}") |
| else: |
| joined = " ".join(f"{float(x): .8g}" for x in np.ravel(row)) |
| print(f" p{p:>5}: {joined}") |
|
|
|
|
| def diagnose_one(ply_path: str) -> dict: |
| data = read_fields(ply_path) |
| scale = data["scale"] |
| opacity = data["opacity"] |
| rot = data["rot"] |
|
|
| exp_scale = np.exp(np.clip(scale, -80.0, 80.0)) |
| alpha = sigmoid(opacity) |
| rot_norm = np.linalg.norm(rot, axis=1) |
| volume = np.exp(np.clip(scale.sum(axis=1), -80.0, 80.0)) |
|
|
| print("\n" + "=" * 88) |
| print(f"PLY: {os.path.abspath(ply_path)}") |
| print(f"N: {data['n']:,}") |
| print("=" * 88) |
|
|
| print_percentiles("scale raw fields: scale_0/1/2", scale) |
| print_percentiles("exp(scale): renderer physical scale if PLY is standard raw scale", exp_scale) |
| print_percentiles("log-volume = scale_0 + scale_1 + scale_2", scale.sum(axis=1)) |
| print_percentiles("physical volume = exp(sum(scale))", volume) |
| print_percentiles("opacity raw field", opacity) |
| print_percentiles("sigmoid(opacity): renderer alpha if PLY is standard raw opacity", alpha) |
| print_percentiles("rotation L2 norm", rot_norm) |
|
|
| suspicious_scale_positive = np.mean(scale > 0.0) |
| suspicious_exp_big = np.mean(exp_scale > 1.0) |
| near_unit_rot = np.mean(np.abs(rot_norm - 1.0) < 1e-3) |
|
|
| print("\n[quick flags]") |
| print(f" fraction(scale entries > 0): {suspicious_scale_positive:.4%}") |
| print(f" fraction(exp(scale) entries > 1): {suspicious_exp_big:.4%}") |
| print(f" fraction(rot norm near 1): {near_unit_rot:.4%}") |
|
|
| if np.percentile(scale, 50) > 0.0: |
| print(" WARN: median raw scale is positive. If this PLY is loaded by standard 3DGS, exp(scale) may be very large.") |
| if np.percentile(exp_scale, 99) > 1.0: |
| print(" WARN: exp(scale) p99 > 1.0. This is often huge for standard 3DGS scenes and can create bright blobs.") |
| if np.percentile(rot_norm, 99) < 0.5 or np.percentile(rot_norm, 1) > 2.0: |
| print(" WARN: rotation norms look unusual before renderer normalization.") |
|
|
| return data |
|
|
|
|
| def compare(original_path: str, compare_path: str) -> None: |
| orig = read_fields(original_path) |
| comp = read_fields(compare_path) |
| if orig["n"] != comp["n"]: |
| print("\n[compare skipped]") |
| print(f" Point counts differ: original={orig['n']:,}, compare={comp['n']:,}") |
| return |
|
|
| scale_a = orig["scale"] |
| scale_b = comp["scale"] |
| rot_a = orig["rot"] |
| rot_b = comp["rot"] |
|
|
| log_volume_delta = scale_b.sum(axis=1) - scale_a.sum(axis=1) |
| volume_ratio = np.exp(np.clip(log_volume_delta, -80.0, 80.0)) |
| scale_abs_err = np.abs(scale_b - scale_a) |
|
|
| rot_a_norm = rot_a / np.linalg.norm(rot_a, axis=1, keepdims=True).clip(1e-12) |
| rot_b_norm = rot_b / np.linalg.norm(rot_b, axis=1, keepdims=True).clip(1e-12) |
| dot = np.abs(np.sum(rot_a_norm * rot_b_norm, axis=1)).clip(0.0, 1.0) |
| rot_angle_deg = np.degrees(2.0 * np.arccos(dot)) |
|
|
| print("\n" + "=" * 88) |
| print("COMPARISON") |
| print(f"original: {os.path.abspath(original_path)}") |
| print(f"compare: {os.path.abspath(compare_path)}") |
| print("=" * 88) |
| print_percentiles("abs scale error per axis", scale_abs_err) |
| print_percentiles("log-volume delta: sum(compare_scale - original_scale)", log_volume_delta) |
| print_percentiles("volume ratio: exp(log-volume delta)", volume_ratio) |
| print_percentiles("rotation angular error in degrees, abs(q dot q')", rot_angle_deg) |
|
|
| for threshold in [2, 4, 8, 16, 32, 64]: |
| count = int(np.sum(volume_ratio > threshold)) |
| print(f" count(volume_ratio > {threshold:>2}): {count:,} ({count / len(volume_ratio):.4%})") |
|
|
| top = np.argsort(volume_ratio)[-10:][::-1] |
| print("\n[top 10 volume-ratio points]") |
| print(" idx ratio orig_scale comp_scale") |
| for idx in top: |
| oscale = " ".join(f"{x: .5f}" for x in scale_a[idx]) |
| cscale = " ".join(f"{x: .5f}" for x in scale_b[idx]) |
| print(f" {idx:<8d} {volume_ratio[idx]:>11.4g} [{oscale}] [{cscale}]") |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description="Diagnose 3DGS PLY scale/opacity/rotation fields.") |
| parser.add_argument("ply", help="Original or target PLY to inspect.") |
| parser.add_argument("--compare", help="Optional reconstructed/quantized PLY to compare against the first PLY.") |
| return parser.parse_args() |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| diagnose_one(args.ply) |
| if args.compare: |
| diagnose_one(args.compare) |
| compare(args.ply, args.compare) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|