How to Prevent Model Substitution in AI API Relays: A Guide to Verifiable Inference and Provenance Self-Checks
When you pay for a flagship model through an AI API relay, how can you tell whether the responses actually come from that model? This guide explains why simply asking a model "who are you?" fails, and outlines the limits of common checks such as style comparison, field validation, and inference signatures. It then introduces verifiable inference, where cryptographic proofs let callers confirm that an output was produced by the committed model weights, with the original request intact and the response untampered. The article walks through weight commitments, zero-knowledge proofs, request binding, and the end-to-end verification flow, while also noting practical constraints like proof-generation cost and deployment options such as TEE-based confidential computing. Before such tools are widely available, the article also offers a practical model-provenance self-check workflow based on baselines, logprob sampling, cross-channel comparison, and full logging, plus a checklist for teams and enterprises.
1. Same “Flagship Model” Label, Wildly Different Quality
Many developers have run into this when using AI API relays: the endpoint claims to serve one high-capability model, yet some relays return careful, well-reasoned answers while others can’t even handle simple logic problems. The cause usually comes down to one of three things:
- Model substitution: You pay for a flagship model, but the relay routes your request to a lower-tier model from the same vendor.
- Distilled imitation: Someone collects large volumes of responses from the real model, trains a smaller model to mimic its style, and still labels it as the original model.
- Middle-layer processing: Reduced quantization precision, compressed context, shortened reasoning, or extra restrictions injected into the system prompt.
There’s another wrinkle: some vendors restrict access based on corporate ownership structure, registration location, or industry for compliance reasons. When legitimate demand is blocked, gray-market top-ups and reselling fill the gap. But the source of those accounts and how user data is handled often become harder to trace. If a data leak or content-compliance incident occurs, responsibility may still fall back on the caller.
In all these cases, there’s a missing link: a verifiable chain of causality between the response you received and “the model you actually paid for.”
Common Questions
- How do you detect model substitution in API relays? Don’t just ask “who are you.” Look at interface fields, output stability, and verifiable credentials.
- How do you judge API quality degradation? Compare responses on the same prompts and parameters for quality, latency, output length, and probability distributions.
- How should enterprises choose a model channel? Prioritize contractual accountability, auditable logs, monitoring alerts, and source transparency.
2. Why “Asking It Who It Is” Doesn’t Work
The most intuitive approach is to ask the model directly: “Who are you, and what version are you?” This is nearly useless. A relay only needs to add one line to the system prompt—“You are [flagship model]”—and any model will answer accordingly. Asking a model to state its parameter count or training data just makes it repeat the preset persona.
Community detection approaches generally fall into three categories, each with blind spots:
| Detection Method | What It Can Answer | Evidence Strength | Applicability Limits |
|---|---|---|---|
| Style comparison | Whether the writing style and refusal habits “look like” the target | Weak; affected by sampling parameters, prompts, and task difficulty | Can only flag obvious anomalies, not assign blame |
| Field validation | Whether the response structure is complete | Weak-to-moderate; only shows the “interface looks right” | Cannot prove “the model is right” |
| Inference signature | Whether the request reached a specific vendor’s endpoint | Moderate; hard to distinguish tiers within the same vendor | Cannot stop middle-layer rewrites or replays |
| Verifiable inference | Whether the output came from the committed weights | Strong; cryptographically auditable | Depends on upstream commitments and proof interfaces being available |
More importantly, the first three methods can only infer “roughly similar or not.” They can’t deliver a definitive “yes, it’s the model,” and they can’t produce evidence suitable for holding anyone accountable. Vendors are in a bind too: when users complain that “the model got dumber,” even if the vendor never changed anything, it’s hard for them to prove their innocence.
Cryptography-based verifiable inference aims to replace “trust the relay’s goodwill and the vendor’s claims” with “the caller can independently verify.”
3. The Core Idea: From “Trusting Claims” to “Verifying Proofs”
Verifiable inference attaches a cryptographic proof to every inference result. Anyone holding the proof can independently confirm three things:
- The computation did use a specific committed set of weights.
- The input was exactly the request you sent, with no substitution in between.
- The output was not tampered with mid-transit.
Verification requires neither re-running the inference nor accessing the model weights. In engineering terms, it consists of three parts:
- Commitment: The model provider publishes a “fingerprint” of the weights; any future model swap leaves a trace.
- Proof: The inference executor generates evidence for the specific request.
- Verification: The caller quickly checks locally, typically at low overhead.
4. The Cryptographic Foundation: Commitments, Zero-Knowledge Proofs, and Request Binding
1. Commitment: Seal First, Verify Later
A commitment mechanism works on a “lock first, inspect later” basis. For models, this means serializing the weights in a fixed format and computing a hash—for example, standardizing dtype, quantization scheme, byte order, and parameter ordering—then computing SHA-256. You can also build a Merkle tree and publish only the root hash.
The sample code below illustrates the idea and is not for production use:
import hashlibimport torchdef weight_commitment(state_dict: dict, bits: int = 16) -> str:h = hashlib.sha256()# Must be fixed: parameter name sorting, dtype, byte order, quantization schemefor name in sorted(state_dict):t = state_dict[name].detach().cpu().contiguous()# int8/int16 conversion must avoid overflow and precision ambiguity;# float weights should be quantized under explicit rules, then converted to fixed-length bytes.raw = t.to(torch.int16 if bits == 16 else torch.int8).numpy().tobytes()h.update(name.encode("utf-8"))h.update(raw)return h.hexdigest()
Three key points:
- Complete coverage: The hash must cover all parameters, including easily missed parts such as positional encodings and vocabularies.
- Reproducibility: Serialization must be deterministic, or others will compute a different fingerprint.
- Verifiable timing: Ideally, the commitment should carry a trusted timestamp or be published to an append-only public log, preventing “retroactive disclosure.”
2. Zero-Knowledge Proofs: Proving Correctness Without Revealing Weights
A commitment alone can only prove that “the same weights were used both times.” To further prove that “this output was actually produced by those weights,” you need a zero-knowledge proof.
zkSNARKs are often mentioned. The idea is arithmeticization: first express the model’s forward pass as mathematical constraints, such as matrix multiplications, RMSNorm, Softmax, approximations of activation functions like GELU, and causal masking. The weights serve as the prover’s private input, and the weight commitment serves as the public input. The prover must demonstrate that there exists a set of weights that satisfies all computational constraints and corresponds to the published commitment.
zkSNARKs typically have three properties:
- Succinct: Proof size and verification time do not grow significantly with model size. Note: this means the common verification-side overhead may be just tens of milliseconds or faster, excluding proof generation; complete proof generation for large models can far exceed the inference itself.
- Non-interactive: The proof is returned with the response, and the caller can verify at any time.
- Zero-knowledge: Verification does not leak the weights.
Mainstream schemes usually require a one-time generation of proving and verification parameters, known as a “trusted setup.” If the secret parameters from the setup leak, it may theoretically be possible to forge proofs, which is why multi-party ceremonies with destruction of each party’s share are needed. Some schemes avoid trusted setup, at the cost of larger proofs and more expensive verification.
3. Request Binding: Preventing “Old Proofs” from Being Reused
If a proof only says “the computation was correct” but not “whose request was computed,” a middle layer can collect genuine responses, bundle them with proofs into an “answer bank,” and forward them unchanged for any request. Defense has two layers:
- Include the request fingerprint (full prompt, sampling parameters, random seed) in the circuit constraints.
- Have the caller generate a one-time nonce and require the proof to be bound to it.
This way, each proof is valid only for that specific request, and reusing it across requests fails.
4. A Reusable Minimal Example: Schnorr’s Discrete Logarithm Proof
Below is a runnable toy example to understand “proving knowledge of a secret without revealing the secret.” It is not a production-grade zkSNARK and does not cover large-model forward computation, but its verification logic genuinely checks the relationship between the proof, the commitment, and the challenge.
# Dependencies: pip install pycryptodome# Principle: the prover holds a secret w and publishes commitment h = g^w mod p;# the verifier gives challenge e, and the prover returns z such that g^z == h^e * y mod p.# This corresponds to "knowing the discrete logarithm" without revealing w.from Crypto.Util.number import getPrimep = getPrime(256) # Demo prime; production should use standardized groups and parametersg = 2 # Group generator, simplified for demonstrationw = 1234567 # Toy stand-in for the model provider's private "weights"h = pow(g, w, p) # Public commitmentdef prove(challenge: int):r = 7654321 # Fixed nonce for demo; production must use cryptographically secure randomnessy = pow(g, r, p)e = challengez = (r + e * w) % (p - 1)return y, zdef verify(challenge: int, y: int, z: int) -> bool:e = challengereturn pow(g, z, p) == (pow(h, e, p) * y) % pchallenge = 42y, z = prove(challenge)print(verify(challenge, y, z)) # True# A party that doesn't know w fails verification if they apply the proof with a wrong z or a wrong challenge.print(verify(challenge, y, z + 1)) # False
In a real zkSNARK, “weight commitment plus scalar multiplication” is replaced by “a full arithmetic circuit covering billions of parameter operations.” But for the caller, the verification action can remain simple.
5. The Complete Verifiable Inference Flow
A complete flow can be broken into four steps:
- Publish commitment: The model provider computes a commitment for a versioned, quantized set of weights and publishes the commitment value, weight hash, and a trusted timestamp.
- Send request: The caller generates a request containing the full prompt, sampling parameters, and a one-time nonce, and agrees on a random seed.
- Generate proof: The server runs inference using the weights corresponding to the commitment and generates proof π, demonstrating that the weight hash equals C, the input hash equals H(request), and the output commitment equals H(response).
- Local verification: Using the public verification parameters, the caller checks whether the proof matches this request, the official commitment, and the response they received. If any item doesn’t match, the result is flagged as suspicious.
# Flow illustration (pseudocode): a real system uses specialized proof circuits and librariesdef verifiable_inference(prompt: str, params: dict, server, verifier):nonce = secrets.token_bytes(32)req = {"prompt": prompt, "params": params, "nonce": nonce.hex()}answer, proof = server.infer_with_proof(req)ok = verifier.verify(proof,expected_commitment=proof["commitment"], # Should match the officially published valuerequest=req,answer=answer,)if not ok:raise ValueError("Proof verification failed: possible model substitution or mid-transit tampering")return answer
6. Inevitable Deployment Challenges
It must be acknowledged that this approach still has clear shortcomings:
- High proof cost: Mainstream zero-knowledge proofs often involve large numbers of constraints, with overhead significantly higher than the inference itself. For large language models, complete proof generation is unlikely to be real-time in the short term. Three practical paths exist, each with conditions:
- Sampled proofs: Generate complete proofs for only a fraction of requests. The advantage is low cost; the drawback is reduced coverage, and unsampled requests may still be problematic.
- Commitment and challenge: Publish the weight commitment, have the caller randomly designate a layer or operator, and require the server to provide that part’s intermediate results along with Merkle paths; the verifier checks along the hash path up to the public root. This requires that the challenger can locate weights or intermediate results and that the server is willing to expose the corresponding intermediate artifacts.
- Recursive proofs: Amortize verification cost via proofs of proofs, but this does not eliminate proof-generation overhead; it only aggregates multiple verifications into one.
- Randomness must be fixed: Temperature sampling during decoding introduces randomness; the server must run with the agreed seed, or outputs won’t be reproducible and proofs become meaningless.
- Proofs have coverage boundaries: Pre-input prompt rewrites and post-inference text post-processing are beyond the circuit’s default reach. These risks require guarding both ends: callers construct requests themselves, bind the full request into the proof, and hash-compare outputs.
- Impostors can “opt out”: The mechanism’s effectiveness depends on whether upstream vendors open weight commitments and proof interfaces. Without a commitment, there’s no proof. Conversely, “whether a service can produce verifiable proofs” can itself become a hard metric for evaluating model services. Be aware: commitments can only prove “these weights were used,” not that “these weights weren’t distilled.”
Another route is Trusted Execution Environments (TEE) / confidential computing. It leverages hardware isolation and remote attestation to prove, at relatively low overhead, that “the code did run in a protected environment.”
| Route | Trust Assumptions | Overhead | Main Risks | Applicable Scenarios |
|---|---|---|---|---|
| Zero-knowledge proofs | Mathematical assumptions, trusted or transparent setup | High proof generation, low verification | Circuit bugs, trusted setup leakage | Strong verifiability, offline auditability |
| Trusted execution environments | Chip vendors, firmware, remote attestation services | Low, close to native inference | Side-channel attacks, firmware vulnerabilities | Latency-sensitive, acceptable hardware trust assumptions |
The two routes will coexist for the long term, each serving different trust models.
7. Five Things You Can Do Now: Spotting Red Flags Without “Anti-Counterfeit Codes”
Before verifiable inference becomes widespread, demand-side teams can establish a “model provenance self-check” process.
- Build a baseline: Use official-channel models to collect responses on your own business question sets, recording token-level log probabilities (Logprobs). Logprobs are the log of the model’s probability for each candidate token, and serve as a relatively direct “fingerprint” across models. Prerequisite: If the target channel doesn’t return token logprobs, switch to alternative metrics and note field availability:
- Response text comparison on fixed question sets;
- Response schema validation;
- Output stability (consistency of repeated calls with the same prompt and seed);
- Latency, throughput, and time-to-first-token distributions;
- Refusal rate, format-compliance rate, and tool-call success rate.
- Scheduled sampling: For purchased channels, periodically collect metrics using the same prompts, sampling parameters, and fixed random seeds, then compute cross-entropy or KL divergence against the baseline. If values shift significantly, or differences between tiers from the same vendor suddenly disappear, watch out for “quiet swaps.”
- Cross-comparison: Send the same question to models from multiple different vendors, compare feature distribution differences, and identify channels with anomalous convergence.
- Full logging: Record the model name field, response parameters, response body, time-to-first-token, total response time, and output speed; archive uniformly to object storage, combined with logging services and monitoring alerts. These records serve as both internal audit evidence and a basis for clarifying responsibility when disputes arise.
- Choose trustworthy channels: Prioritize official model services or established cloud platforms with clear contractual accountability. For example, Baidu AI Cloud’s Qianfan model platform connects to multiple mainstream large models, allowing enterprises to select models flexibly through a unified interface and accumulate audit data via call logs, monitoring alerts, and other capabilities; this is an example only and does not constitute endorsement.
Executable Checklist
| Check Item | Recommended Practice | Responsibility |
|---|---|---|
| Sampling frequency | Log every critical-business call; sample daily or weekly for routine business | Business team + Platform team |
| Baseline version | Record official model version, quantization scheme, prompt templates | Algorithm/Evaluation team |
| Alert thresholds | Logprob drift, latency P95, abnormal refusal-rate swings | SRE/Monitoring team |
| Logging fields | Request, response, model name, parameters, timing, random seed | Caller + Channel provider |
| Exception handling | Isolate the channel first, then cross-verify, then pursue contractual accountability | Procurement + Security + Legal |
8. Conclusion: Anti-Counterfeit Codes Are Great, but the Decision Is Yours
The core tension in AI model “anti-counterfeiting” is who generates the response and whether it can be proven. Relying solely on “asking it who it is” is doomed to fail, because personas can be faked. Style comparison, field validation, and inference signatures can only serve as circumstantial evidence, not definitive conclusions.
Verifiable inference offers another path: the model provider publishes weight commitments, the executor attaches a zero-knowledge proof to each inference, and the caller locally verifies whether “the response came from the committed weights.” It can’t eliminate distillation, nor can it stop malicious parties from opting out, but it turns “model substitution” from something hard to detect into something verifiable at a glance.
For developers and enterprises, the more realistic approach is two-pronged: on one hand, build your own quality defense through baseline evaluations, Logprob or alternative-metric sampling, multi-channel cross-validation, and full logging; on the other hand, prioritize model services with transparent sources and clear accountability, and keep an eye on the standardization and engineering progress of verifiable inference.
As “trust” is gradually replaced by “verification,” the API market will shift from competing on who tells a better story to competing on who can withstand scrutiny.
