Audit mobile speech heads and S25 VLA latent impact
This commit is contained in:
1 parent
1949c31f80
commit
d71d39f656
53 files changed
+3333
-30
No files matched your search
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Audit one MiniCPM-o speech-head decode step against pinned ONNX CPU tensors."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
SOURCE_SHA256 = "78cf64804f11ad269ee4180da61588ccc5eefe2942773227345499756e4cc229"
|
||||
FIXTURE_SHA256 = "65919ea1f351feec33c1415a3e3db76d60bc9c2beb3d49a72af75dcb418e83b4"
|
||||
REFERENCE_SHA256 = "902adcceadbe761d938ef2ade51cf953c8917ea1abfaee33a10c84e300c1bd96"
|
||||
COMPILE_OPTIONS = {
|
||||
"--target_runtime qnn_context_binary --quantize_full_type float16",
|
||||
"--target_runtime qnn_dlc --qnn_options default_graph_htp_precision=FLOAT16",
|
||||
}
|
||||
INPUT_NAMES = ["x", "cos", "sin", "mask"] + [
|
||||
name for layer in range(20) for name in (f"k_cache_{layer}", f"v_cache_{layer}")
|
||||
]
|
||||
OUTPUT_NAMES = ["logits"] + [
|
||||
name for layer in range(20) for name in (f"k_new_{layer}", f"v_new_{layer}")
|
||||
]
|
||||
|
||||
|
||||
def file_record(path: Path) -> dict:
|
||||
with path.open("rb") as source:
|
||||
digest = hashlib.file_digest(source, "sha256").hexdigest()
|
||||
return {"bytes": path.stat().st_size, "sha256": digest}
|
||||
|
||||
|
||||
def read_array(data: np.lib.npyio.NpzFile, name: str, shape: tuple[int, ...]) -> np.ndarray:
|
||||
value = np.asarray(data[name])
|
||||
if value.shape != shape or value.dtype != np.float32 or not np.isfinite(value).all():
|
||||
raise ValueError(f"{name}: expected finite FP32 {shape}, got {value.shape}/{value.dtype}")
|
||||
return value
|
||||
|
||||
|
||||
def compare(reference: np.ndarray, actual: np.ndarray) -> dict:
|
||||
source = reference.astype(np.float64).ravel()
|
||||
observed = actual.astype(np.float64).ravel()
|
||||
error = source - observed
|
||||
source_norm = float(np.linalg.norm(source))
|
||||
error_norm = float(np.linalg.norm(error))
|
||||
return {
|
||||
"relative_l2": error_norm / source_norm if source_norm else (0.0 if error_norm == 0 else None),
|
||||
"max_abs_error": float(np.max(np.abs(error))),
|
||||
"source_rms": float(np.sqrt(np.mean(source * source))),
|
||||
"device_rms": float(np.sqrt(np.mean(observed * observed))),
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--device-name", required=True)
|
||||
parser.add_argument("--source-onnx", type=Path, required=True)
|
||||
parser.add_argument("--fixture", type=Path, required=True)
|
||||
parser.add_argument("--cpu-reference", type=Path, required=True)
|
||||
parser.add_argument("--compile-report", type=Path, required=True)
|
||||
parser.add_argument("--inference-report", type=Path, required=True)
|
||||
parser.add_argument("--device-output", type=Path, required=True)
|
||||
parser.add_argument("--output-report", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
compiled = json.loads(args.compile_report.read_text(encoding="utf-8"))
|
||||
inferred = json.loads(args.inference_report.read_text(encoding="utf-8"))
|
||||
if compiled.get("status") != "SUCCESS" or inferred.get("status") != "SUCCESS":
|
||||
raise ValueError("compile and inference must be terminal successes")
|
||||
if compiled.get("source_model_id") != "mn4gjjpvn" or compiled.get("options") not in COMPILE_OPTIONS:
|
||||
raise ValueError("compile source/options differ from the pinned speech-head artifact")
|
||||
if inferred.get("model_id") != compiled.get("target_model_id"):
|
||||
raise ValueError("inference used a different target artifact")
|
||||
if inferred.get("input_dataset_id") not in {"d7gwxe3y2", "d7zn8rk57"}:
|
||||
raise ValueError("inference did not use a retained matching fixture dataset")
|
||||
if (compiled.get("device", {}).get("name") != args.device_name
|
||||
or inferred.get("device", {}).get("name") != args.device_name):
|
||||
raise ValueError("jobs did not use the exact requested device")
|
||||
|
||||
files = {
|
||||
name: file_record(path)
|
||||
for name, path in {
|
||||
"source_onnx": args.source_onnx,
|
||||
"fixture": args.fixture,
|
||||
"cpu_reference": args.cpu_reference,
|
||||
"device_output": args.device_output,
|
||||
}.items()
|
||||
}
|
||||
for name, expected in {
|
||||
"source_onnx": SOURCE_SHA256,
|
||||
"fixture": FIXTURE_SHA256,
|
||||
"cpu_reference": REFERENCE_SHA256,
|
||||
}.items():
|
||||
if files[name]["sha256"] != expected:
|
||||
raise ValueError(f"{name} differs from the pinned artifact")
|
||||
|
||||
with np.load(args.fixture, allow_pickle=False) as fixture:
|
||||
if fixture.files != INPUT_NAMES:
|
||||
raise ValueError("fixture input names/order differ")
|
||||
read_array(fixture, "x", (1, 1, 768))
|
||||
for name in ("cos", "sin"):
|
||||
read_array(fixture, name, (1, 1, 1, 64))
|
||||
read_array(fixture, "mask", (1, 1, 1, 257))
|
||||
for name in INPUT_NAMES[4:]:
|
||||
read_array(fixture, name, (1, 12, 256, 64))
|
||||
|
||||
comparisons = {}
|
||||
with np.load(args.cpu_reference, allow_pickle=False) as reference, np.load(
|
||||
args.device_output, allow_pickle=False
|
||||
) as output:
|
||||
if reference.files != OUTPUT_NAMES:
|
||||
raise ValueError("CPU output names/order differ")
|
||||
expected_keys = [f"output_{index}__0" for index in range(len(OUTPUT_NAMES))]
|
||||
if output.files != expected_keys:
|
||||
raise ValueError("device output names/order differ")
|
||||
for index, name in enumerate(OUTPUT_NAMES):
|
||||
shape = (1, 6562) if index == 0 else (1, 12, 1, 64)
|
||||
source_value = read_array(reference, name, shape)
|
||||
device_value = read_array(output, expected_keys[index], shape)
|
||||
comparisons[name] = compare(source_value, device_value)
|
||||
if name == "logits":
|
||||
comparisons[name]["cpu_top1"] = int(np.argmax(source_value[0]))
|
||||
comparisons[name]["device_top1"] = int(np.argmax(device_value[0]))
|
||||
comparisons[name]["top1_matches"] = bool(
|
||||
comparisons[name]["cpu_top1"] == comparisons[name]["device_top1"]
|
||||
)
|
||||
|
||||
report = {
|
||||
"scope": "one fixed-cache 20-layer MiniCPM-o speech-head decode step; no complete multimodal stream",
|
||||
"status": "component_inference_numeric_measured",
|
||||
"device": inferred["device"],
|
||||
"compile_job_id": compiled["job_id"],
|
||||
"inference_job_id": inferred["job_id"],
|
||||
"source_model_id": compiled["source_model_id"],
|
||||
"target_model_id": compiled["target_model_id"],
|
||||
"input_dataset_id": inferred["input_dataset_id"],
|
||||
"requested_run_options": inferred["options"],
|
||||
"files": files,
|
||||
"tensor_comparison": comparisons,
|
||||
"cache_max_relative_l2": max(comparisons[name]["relative_l2"] for name in OUTPUT_NAMES[1:]),
|
||||
"limits": [
|
||||
"The historical ONNX export does not attest the exact source checkpoint revision.",
|
||||
"One retained decode fixture cannot establish speech-token or generated-audio quality.",
|
||||
"Actual NPU placement requires a device profile; a request or QNN artifact alone is insufficient.",
|
||||
"Thinker, audio/vision encoders, vocoder, state loop and complete Omni request were not tested.",
|
||||
],
|
||||
}
|
||||
args.output_report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps({
|
||||
"status": report["status"],
|
||||
"device": report["device"]["name"],
|
||||
"logits": comparisons["logits"],
|
||||
"cache_max_relative_l2": report["cache_max_relative_l2"],
|
||||
}, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -59,17 +59,20 @@ def main() -> None:
|
||||
parser.add_argument("--inference-report", type=Path, required=True)
|
||||
parser.add_argument("--device-output", type=Path, required=True)
|
||||
parser.add_argument("--output-report", type=Path, required=True)
|
||||
parser.add_argument("--expected-compile-options", default=COMPILE_OPTIONS)
|
||||
parser.add_argument("--expected-run-options", default="--compute_unit npu")
|
||||
args = parser.parse_args()
|
||||
|
||||
compiled = json.loads(args.compile_report.read_text(encoding="utf-8"))
|
||||
inferred = json.loads(args.inference_report.read_text(encoding="utf-8"))
|
||||
if compiled.get("status") != "SUCCESS" or inferred.get("status") != "SUCCESS":
|
||||
raise ValueError("compile and inference must both be terminal successes")
|
||||
if compiled.get("source_model_id") != "mq3xre4rq" or compiled.get("options") != COMPILE_OPTIONS:
|
||||
if compiled.get("source_model_id") != "mq3xre4rq" or compiled.get("options") != args.expected_compile_options:
|
||||
raise ValueError("compile source or options differ from the pinned talker artifact")
|
||||
if inferred.get("model_id") != compiled.get("target_model_id"):
|
||||
raise ValueError("inference did not use the audited target artifact")
|
||||
if inferred.get("input_dataset_id") != "d7dw6pgy2" or inferred.get("options") != "--compute_unit npu":
|
||||
if (inferred.get("input_dataset_id") != "d7dw6pgy2"
|
||||
or inferred.get("options") != args.expected_run_options):
|
||||
raise ValueError("inference fixture or requested compute unit differs")
|
||||
if inferred.get("device") != compiled.get("device"):
|
||||
raise ValueError("compile/inference device metadata differs")
|
||||
@@ -140,7 +143,7 @@ def main() -> None:
|
||||
"limits": [
|
||||
"The historical source export does not attest an exact checkpoint revision.",
|
||||
"The fixture is synthetic and has no token-to-audio quality tolerance.",
|
||||
"Requested NPU is not actual placement without a device profile.",
|
||||
"Requested compute unit is not actual placement without a device profile.",
|
||||
"No predictor, vocoder, persistent cache loop or complete TTS stream was tested.",
|
||||
],
|
||||
}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure policy-action sensitivity to a hosted Cosmos encoder latent.
|
||||
|
||||
The full policy runs on local CPU with identical synthetic state/noise. Its
|
||||
encoder is replaced by pinned source/device latent tensors from one fixture.
|
||||
This is a numerical handoff probe, not a device-local or robot-task run.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
CHECKPOINT_SHA256 = "586799539888c69c35f84d083e559cc5f0ba887801d000e70e65f58d3f85c313"
|
||||
FIXTURE_SHA256 = "dcbaf1391ca914d4bbccc1cb384daf05666e771d9cdae90c4f069ec8fcf05368"
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
with path.open("rb") as source:
|
||||
return hashlib.file_digest(source, "sha256").hexdigest()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
for name in ("model-dir", "cosmos-dir", "processor-dir", "fixture", "device-output", "audit-report", "output"):
|
||||
parser.add_argument(f"--{name}", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
os.environ["INTERNVLA_A1_COSMOS_DIR"] = str(args.cosmos_dir.resolve(strict=True))
|
||||
os.environ["INTERNVLA_A1_PROCESSOR_DIR"] = str(args.processor_dir.resolve(strict=True))
|
||||
os.environ["HF_HUB_OFFLINE"] = "1"
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.registry import initialize_model
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
checkpoint = args.model_dir / "model.safetensors"
|
||||
if sha256(checkpoint) != CHECKPOINT_SHA256 or sha256(args.fixture) != FIXTURE_SHA256:
|
||||
raise ValueError("checkpoint or encoder fixture differs from pinned source")
|
||||
audit = json.loads(args.audit_report.read_text(encoding="utf-8"))
|
||||
if (audit.get("status") != "component_inference_numeric_measured"
|
||||
or audit.get("device", {}).get("name") != "Samsung Galaxy S25"
|
||||
or audit.get("files", {}).get("device_output", {}).get("sha256") != sha256(args.device_output)):
|
||||
raise ValueError("hosted latent lacks audited S25 provenance")
|
||||
with np.load(args.fixture, allow_pickle=False) as fixture:
|
||||
source_latent = np.asarray(fixture["pattern_reference"])
|
||||
with np.load(args.device_output, allow_pickle=False) as output:
|
||||
if output.files != ["output_0__0"]:
|
||||
raise ValueError("unexpected hosted output layout")
|
||||
device_latent = np.asarray(output["output_0__0"])
|
||||
if (source_latent.shape != (6, 16, 32, 32) or device_latent.shape != source_latent.shape
|
||||
or source_latent.dtype != np.float32 or device_latent.dtype != np.float32
|
||||
or not np.isfinite(source_latent).all() or not np.isfinite(device_latent).all()):
|
||||
raise ValueError("latents violate the finite FP32 six-frame contract")
|
||||
|
||||
config = OmniDiffusionConfig(
|
||||
model=str(args.model_dir.resolve(strict=True)),
|
||||
model_class_name="InternVLAA1Pipeline",
|
||||
dtype=torch.bfloat16,
|
||||
custom_pipeline_args={
|
||||
"device": "cpu", "dtype": "bfloat16", "compile_model": False,
|
||||
"enable_regional_compile": False, "enable_warmup": False,
|
||||
"strict_load": True,
|
||||
"processor_model_name": str(args.processor_dir.resolve(strict=True)),
|
||||
},
|
||||
)
|
||||
started = time.perf_counter()
|
||||
pipeline = initialize_model(config)
|
||||
load_seconds = time.perf_counter() - started
|
||||
if pipeline.runtime_mode() != "real_checkpoint_loaded":
|
||||
raise RuntimeError("real policy checkpoint was not loaded")
|
||||
if {parameter.device.type for parameter in pipeline.policy.parameters()} != {"cpu"}:
|
||||
raise RuntimeError("policy parameters did not stay on CPU")
|
||||
inputs = pipeline._build_fake_batch_inputs()
|
||||
noise = torch.zeros((1, pipeline.config.chunk_size, pipeline.config.max_action_dim), dtype=torch.float32)
|
||||
cosmos = pipeline.policy.model.cosmos
|
||||
original_encoder = cosmos._enc_model
|
||||
|
||||
class PinnedLatent(torch.nn.Module):
|
||||
def __init__(self, latent: np.ndarray) -> None:
|
||||
super().__init__()
|
||||
self.latent = torch.from_numpy(latent.copy())
|
||||
self.calls = 0
|
||||
|
||||
def forward(self, pixels: torch.Tensor) -> torch.Tensor:
|
||||
if tuple(pixels.shape) != (6, 3, 256, 256) or pixels.device.type != "cpu":
|
||||
raise RuntimeError("unexpected policy encoder input")
|
||||
self.calls += 1
|
||||
return self.latent.to(dtype=pixels.dtype)
|
||||
|
||||
def actions(encoder: PinnedLatent) -> np.ndarray:
|
||||
cosmos._enc_model = encoder
|
||||
result = pipeline.forward(DiffusionRequestBatch(requests=[
|
||||
OmniDiffusionRequest(
|
||||
prompt="",
|
||||
sampling_params=OmniDiffusionSamplingParams(extra_args={
|
||||
"batch_inputs": inputs, "noise": noise, "decode_image": False,
|
||||
}),
|
||||
request_id="internvla-hosted-latent-synthetic",
|
||||
)
|
||||
]))
|
||||
if result.error:
|
||||
raise RuntimeError(result.error)
|
||||
tensor = result.output["payload"]["actions"]
|
||||
if tuple(tensor.shape) != (1, 50, 32) or tensor.device.type != "cpu" or not torch.isfinite(tensor).all():
|
||||
raise RuntimeError("bad policy action tensor")
|
||||
return tensor.detach().float().cpu().contiguous().numpy()
|
||||
|
||||
source_encoder = PinnedLatent(source_latent)
|
||||
hosted_encoder = PinnedLatent(device_latent)
|
||||
try:
|
||||
source_actions = actions(source_encoder)
|
||||
hosted_actions = actions(hosted_encoder)
|
||||
source_repeat = actions(source_encoder)
|
||||
finally:
|
||||
cosmos._enc_model = original_encoder
|
||||
if not np.array_equal(source_actions, source_repeat):
|
||||
raise RuntimeError("CPU source policy changed across the paired calls")
|
||||
source = source_actions.astype(np.float64).ravel()
|
||||
hosted = hosted_actions.astype(np.float64).ravel()
|
||||
delta = source - hosted
|
||||
report = {
|
||||
"scope": "S25 hosted Cosmos latent injected into local CPU InternVLA policy with synthetic state/noise; no device-local policy or robot-task result",
|
||||
"status": "synthetic_action_sensitivity_measured",
|
||||
"policy_checkpoint_sha256": CHECKPOINT_SHA256,
|
||||
"fixture_sha256": FIXTURE_SHA256,
|
||||
"hosted_output_sha256": sha256(args.device_output),
|
||||
"hosted_inference_job_id": audit["inference_job_id"],
|
||||
"policy_torch": torch.__version__,
|
||||
"policy_load_seconds_not_request_timing": load_seconds,
|
||||
"encoder_calls": {"source": source_encoder.calls, "hosted": hosted_encoder.calls},
|
||||
"action_shape": list(source_actions.shape),
|
||||
"source_repeat_bitwise_equal": True,
|
||||
"action_relative_l2": float(np.linalg.norm(delta) / np.linalg.norm(source)),
|
||||
"action_max_abs": float(np.max(np.abs(delta))),
|
||||
"action_cosine": float(np.dot(source, hosted) / (np.linalg.norm(source) * np.linalg.norm(hosted))),
|
||||
"source_actions_sha256": hashlib.sha256(source_actions.tobytes()).hexdigest(),
|
||||
"hosted_actions_sha256": hashlib.sha256(hosted_actions.tobytes()).hexdigest(),
|
||||
"limits": [
|
||||
"The policy ran on local CPU; the device only executed the isolated encoder fixture.",
|
||||
"The encoder input was a synthetic pattern and policy state/noise were synthetic zeros.",
|
||||
"No real-observation reference actions, physical units/time, or robot-task tolerance exist.",
|
||||
"No latency, memory admission, cancellation or sustained device power gate was tested.",
|
||||
],
|
||||
}
|
||||
args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps({key: report[key] for key in (
|
||||
"status", "action_relative_l2", "action_max_abs", "action_cosine", "source_repeat_bitwise_equal"
|
||||
)}, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user