# Requantization clamp

> Sort how the MNIST network squeezes a 32-bit sum into an 8-bit value, so no value ever falls outside 0 to 255.

Inspired by UOR-Foundation/MNIST (https://github.com/UOR-Foundation/MNIST). The ONNX Model Zoo int8 MNIST network as one LexLean model, certified into a Rust package that matches onnxruntime on all 10,000 test images. Pattern: Decision table, OMG DMN 1.5, hit policy FIRST. To write one of your own, follow How to build a decision table app (../../guides/decision-table/index.md). The prompt below is data, quoted from the example.

**Figure: What the Requantization clamp app does.** A request goes in, the rules decide, and the Lean kernel has already proved what the rules promise.

| Step | What happens |
| --- | --- |
| 1. Request | sign, q |
| 2. 2 rules | the first that matches wins |
| 3. Answer | floor, passed, ceiling |
| 4. Proved | 3 theorems, 25 tests |

Verified by prismpm verify in the pinned SDK. Fingerprint: 1e3883baecfce7dab834f7ed28ca2eeae32346d3356563f6ee69cc65b75619d0. Acceptance vectors: 25. Claims: 6.

## The prompt

```json
{
  "schema": "prism/prompt/1",
  "pattern": "decisionTable",
  "goal": "Sort how the MNIST network squeezes a 32-bit sum into an 8-bit value, so no value ever falls outside 0 to 255.",
  "repository": "UOR-Foundation/MNIST",
  "app": {
    "name": "mnist-requant-clamp",
    "title": "Requantization clamp",
    "purpose": "Classify the scaled accumulator q of one requantized activation, from its sign and magnitude, as clamped to the floor 0, passed through unchanged, or clamped to the ceiling 255.",
    "fields": [
      {
        "name": "sign",
        "kind": "choice",
        "values": [
          "negative",
          "nonnegative"
        ],
        "means": "the sign of q = ((acc + bias) * M + 2^31 + Z * 2^32) quot 2^32"
      },
      {
        "name": "q",
        "kind": "number",
        "min": 0,
        "max": 2147483648,
        "means": "the magnitude of q, bounded by the 32-bit fixed-point range"
      }
    ],
    "outcomes": [
      "floor",
      "passed",
      "ceiling"
    ],
    "meanings": {
      "floor": "q is below 0 and the code is 0, the uint8 zero point",
      "passed": "q is already a uint8 code and is kept",
      "ceiling": "q is above 255 and the code is 255"
    },
    "rules": [
      {
        "when": [
          {
            "field": "sign",
            "op": "is",
            "value": "negative"
          },
          {
            "field": "q",
            "op": ">",
            "value": 0
          }
        ],
        "then": "floor",
        "why": "src/Mnist/Core.lex.tex requant: lo = if q < 0 then 0 else q"
      },
      {
        "when": [
          {
            "field": "q",
            "op": ">",
            "value": 255
          }
        ],
        "then": "ceiling",
        "why": "src/Mnist/Core.lex.tex requant: hi = if 255 < lo then 255 else lo"
      }
    ],
    "otherwise": "passed",
    "otherwiseWhy": "src/Mnist/Core.lex.tex requant: a q in 0..255 is returned as the activation code; README.md: uint8 activations with zero point 0",
    "properties": [
      {
        "kind": "never",
        "when": [
          {
            "field": "sign",
            "op": "is",
            "value": "negative"
          },
          {
            "field": "q",
            "op": ">",
            "value": 0
          }
        ],
        "then": "passed",
        "why": "a negative accumulator never becomes a positive code"
      },
      {
        "kind": "never",
        "when": [
          {
            "field": "sign",
            "op": "is",
            "value": "nonnegative"
          },
          {
            "field": "q",
            "op": ">",
            "value": 255
          }
        ],
        "then": "passed",
        "why": "no activation exceeds 255"
      },
      {
        "kind": "always",
        "when": [
          {
            "field": "q",
            "op": "<=",
            "value": 255
          },
          {
            "field": "sign",
            "op": "is",
            "value": "nonnegative"
          }
        ],
        "then": "passed",
        "why": "an in-range code is never altered"
      }
    ],
    "examples": [
      {
        "request": "nonnegative 0",
        "response": "passed"
      },
      {
        "request": "nonnegative 7",
        "response": "passed"
      },
      {
        "request": "nonnegative 255",
        "response": "passed"
      },
      {
        "request": "nonnegative 256",
        "response": "ceiling"
      },
      {
        "request": "negative 1",
        "response": "floor"
      },
      {
        "request": "negative 0",
        "response": "passed"
      },
      {
        "request": "negative 4096",
        "response": "floor"
      }
    ]
  },
  "stakeholders": [
    {
      "name": "Model auditor",
      "text": "Checks that the LexLean network computes exactly what mnist-12-int8.onnx computes, layer by layer.",
      "concerns": [
        "Correct answers",
        "Proved guarantees"
      ]
    },
    {
      "name": "Package integrator",
      "text": "Embeds the certified rust-std mnist package and needs every activation to be a uint8 code.",
      "concerns": [
        "Proved guarantees",
        "Refused malformed requests"
      ]
    }
  ],
  "components": [
    {
      "name": "onnxruntime",
      "text": "onnxruntime 1.29.0, whose class on all 10,000 test images is the authority (MN-05).",
      "kind": "externalSystem"
    },
    {
      "name": "mnist package",
      "text": "The certified rust-std package in dist/ exporting run(Bytes).",
      "kind": "releaseBinary"
    }
  ],
  "threats": [
    {
      "name": "Activation wraps past 255",
      "text": "A large accumulator is truncated to 8 bits instead of saturating, changing the class.",
      "stride": "tampering",
      "asset": "answer",
      "likelihood": "medium",
      "impact": "major",
      "control": {
        "name": "Saturating ceiling",
        "text": "q above 255 is clamped to 255.",
        "evidence": [
          {
            "kind": "proof",
            "reference": "MnistRequantClampProofs::inv002Holds"
          },
          {
            "kind": "gate",
            "reference": "UOR-Foundation/MNIST MN-05: class equal to onnxruntime on 10,000 images"
          }
        ]
      }
    },
    {
      "name": "Negative activation",
      "text": "A negative accumulator passes as a large unsigned code.",
      "stride": "tampering",
      "asset": "answer",
      "likelihood": "medium",
      "impact": "major",
      "control": {
        "name": "Floor at the zero point",
        "text": "Negative q is clamped to 0.",
        "evidence": [
          {
            "kind": "proof",
            "reference": "MnistRequantClampProofs::inv001Holds"
          }
        ]
      }
    },
    {
      "name": "Accumulator overflow",
      "text": "The accumulator itself overflows before requantization.",
      "stride": "denialOfService",
      "asset": "request",
      "likelihood": "low",
      "impact": "major",
      "accepted": "README.md says so: that the accumulators never overflow is not a theorem; the overflow effect stays declared and checked at every operation."
    }
  ],
  "quality": [
    {
      "characteristic": "Functional suitability",
      "subcharacteristic": "Functional correctness",
      "requirement": "Codes fit uint8",
      "text": "Every activation code lies in 0..255.",
      "measure": "Largest activation code",
      "measureText": "The largest code any request is answered with.",
      "threshold": 255
    },
    {
      "characteristic": "Functional suitability",
      "subcharacteristic": "Functional appropriateness",
      "requirement": "Class agrees with the authority",
      "text": "The package returns onnxruntime's class on every test image, as MN-05 gates.",
      "measure": "Class disagreements",
      "measureText": "Test images whose class differs from onnxruntime 1.29.0.",
      "threshold": 0
    }
  ],
  "journeys": [
    {
      "stakeholder": "Model auditor",
      "steps": [
        "REQ-001",
        "REQ-002",
        "otherwise",
        "INV-003"
      ]
    },
    {
      "stakeholder": "Package integrator",
      "steps": [
        "INV-001",
        "INV-002",
        "refuse"
      ]
    }
  ],
  "axioms": {
    "inv001Holds": [
      "Classical.choice",
      "Quot.sound",
      "propext"
    ]
  },
  "concerns": [],
  "license": "MIT OR Apache-2.0"
}
```

## Claims

- MR-01: The app never answers passed when sign is negative and q is above 0
- MR-02: The app never answers passed when sign is nonnegative and q is above 255
- MR-03: The app always answers passed when q is at most 255 and sign is nonnegative
- MR-04: The architecture description declares every stakeholder, concern, component, edge, viewpoint and view it references
- MR-05: The ISO/IEC 25010 quality model numbers every characteristic, subcharacteristic, requirement and measure, and every parent it names is declared
- MR-06: Every compliance obligation is numbered in order and names its evidence

## Pattern

Decision table: OMG DMN 1.5, hit policy FIRST. The rules are tried in order, and the first one that matches gives the answer. If none matches, the default answer applies. This is a DMN decision table with the FIRST hit policy.

| Pattern | Standard | Answers |
| --- | --- | --- |
| Decision table | OMG DMN 1.5, hit policy FIRST | floor, passed, ceiling |

**Figure: Rules for each answer.** Each bar counts the rules that give one answer. When no rule matches, the answer is passed.

|  | rules |
| --- | --- |
| floor | 1 |
| passed | 0 |
| ceiling | 1 |

## Behavior

A request is sign, q, separated by spaces. The first rule that matches decides. If none matches, the answer is passed. A request over 64 bytes, or in any other form, is answered invalid.

| Rule | When | Answer | Why |
| --- | --- | --- | --- |
| REQ-001 | sign is negative and q is above 0 | floor | src/Mnist/Core.lex.tex requant: lo = if q \< 0 then 0 else q |
| REQ-002 | q is above 255 | ceiling | src/Mnist/Core.lex.tex requant: hi = if 255 \< lo then 255 else lo |
| otherwise | no rule matches | passed | src/Mnist/Core.lex.tex requant: a q in 0..255 is returned as the activation code; README.md: uint8 activations with zero point 0 |

## Properties Lean proves

Each property is a theorem about the same definitions the app is built from. It is proved for every request, not only the tested ones.

| Property | Statement | Theorem | Why |
| --- | --- | --- | --- |
| INV-001 | It never answers passed when sign is negative and q is above 0. | MnistRequantClampProofs::inv001Holds | a negative accumulator never becomes a positive code |
| INV-002 | It never answers passed when sign is nonnegative and q is above 255. | MnistRequantClampProofs::inv002Holds | no activation exceeds 255 |
| INV-003 | It always answers passed when q is at most 255 and sign is nonnegative. | MnistRequantClampProofs::inv003Holds | an in-range code is never altered |

## Architecture

Stakeholders and the concerns each one views the app through (ISO/IEC/IEEE 42010).

| Stakeholder | Who they are | Concerns |
| --- | --- | --- |
| Model auditor | Checks that the LexLean network computes exactly what mnist-12-int8.onnx computes, layer by layer. | Correct answers, Proved guarantees |
| Package integrator | Embeds the certified rust-std mnist package and needs every activation to be a uint8 code. | Proved guarantees, Refused malformed requests |
| Verifier | Anyone who loads the holo, checks its fingerprint and replays its acceptance vectors before trusting an answer. | Integrity of the published app, Refused malformed requests, Proved guarantees |

## Concerns

What the stakeholders care about, and the model each is viewed in.

| Concern | What it means | Model |
| --- | --- | --- |
| Correct answers | Every well-formed request is answered by the first rule that matches it, or passed when none does, as the spec states. | quality |
| Integrity of the published app | What a visitor runs is the holo the build verified, with its fingerprint and signed provenance beside it. | security |
| Proved guarantees | Each of the 3 properties of the spec holds for every request, proved by the Lean kernel. | quality |
| Refused malformed requests | A request that is not the 2 fields in order, or is longer than 64 bytes, is answered invalid and never guessed. | security |

## Components

8 components and 11 edges between them.

| Component | Kind | What it is |
| --- | --- | --- |
| Browser | externalSystem | The visitor's web browser, which loads the page and runs the Requantization clamp guest. |
| GitHub Pages | externalSystem | Serves the page and the holo from the repository Pages workflow. |
| mnist package | releaseBinary | The certified rust-std package in dist/ exporting run(Bytes). |
| onnxruntime | externalSystem | onnxruntime 1.29.0, whose class on all 10,000 test images is the authority (MN-05). |
| Prism build | cliAdapter | prismpm verify in the SDK image prismpm.lock pins: it checks every theorem, builds the guest and replays every vector. |
| Requantization clamp guest | service | The Core-Wasm guest built from the model: it answers one request of at most 64 bytes with one answer of at most 64. |
| Requantization clamp page | staticSite | The page the template publishes: the holo, its fingerprint, its provenance and its acceptance vectors. |
| Source repository | externalSystem | The repository that holds the prompt, the model and its gate. |

## Design views

The SDK checks each view against the system model and draws it as OPL and PlantUML.

| View | Diagram | Viewpoint |
| --- | --- | --- |
| Deciding a Requantization clamp request | opmObjectProcess | Model auditor: Correct answers |
| Components of Requantization clamp | umlComponent | Verifier: Integrity of the published app |
| Answering a Requantization clamp request | umlSequence | Model auditor: Correct answers |
| States of the Requantization clamp guest | umlStateMachine | Package integrator: Refused malformed requests |

## Features and journeys

7 features. Each names the definitions that do the work and the tests that accept it. Each stakeholder has one journey.

| Feature | Calls | Accepted by |
| --- | --- | --- |
| When sign is negative and q is above 0, the answer is floor. | MnistRequantClamp::rule1, MnistRequantClamp::judge | MnistRequantClamp::application |
| When q is above 255, the answer is ceiling. | MnistRequantClamp::rule2, MnistRequantClamp::judge | MnistRequantClamp::application |
| When no rule matches, the answer is passed. | MnistRequantClamp::judge | MnistRequantClamp::application |
| A request that is not sign, q in order, separated by single spaces, or is over 64 bytes, is answered invalid. | MnistRequantClamp::dispatch, MnistRequantClamp::decodeField1 | MnistRequantClamp::application |
| It never answers passed when sign is negative and q is above 0. | MnistRequantClamp::judge | MnistRequantClampProofs::inv001Holds |
| It never answers passed when sign is nonnegative and q is above 255. | MnistRequantClamp::judge | MnistRequantClampProofs::inv002Holds |
| It always answers passed when q is at most 255 and sign is nonnegative. | MnistRequantClamp::judge | MnistRequantClampProofs::inv003Holds |

## Journeys

The ordered features each stakeholder takes.

| Stakeholder | Steps |
| --- | --- |
| Model auditor | REQ-001 → REQ-002 → otherwise → INV-003 |
| Package integrator | INV-001 → INV-002 → refuse |
| Verifier | refuse → INV-001 → INV-002 → INV-003 |

## Security and threat model

12 threats against 4 assets. Each has a STRIDE category, and either a control with evidence or a risk that is accepted on purpose.

| Threat | STRIDE | Asset | Risk | Answered by |
| --- | --- | --- | --- | --- |
| Accumulator overflow | denialOfService | Request bytes | low likelihood, major impact | accepted: README.md says so: that the accumulators never overflow is not a theorem; the overflow effect stays declared and checked at every operation. |
| Activation wraps past 255 | tampering | Answer | medium likelihood, major impact | Saturating ceiling: proof MnistRequantClampProofs::inv002Holds; gate UOR-Foundation/MNIST MN-05: class equal to onnxruntime on 10,000 images |
| Answer that breaks INV-001 | repudiation | Answer | medium likelihood, critical impact | Proof of INV-001: proof MnistRequantClampProofs::inv001Holds |
| Answer that breaks INV-002 | repudiation | Answer | medium likelihood, critical impact | Proof of INV-002: proof MnistRequantClampProofs::inv002Holds |
| Answer that breaks INV-003 | repudiation | Answer | medium likelihood, critical impact | Proof of INV-003: proof MnistRequantClampProofs::inv003Holds |
| Granted capability | informationDisclosure | Answer | low likelihood, major impact | No capability granted: gate prism-code check refuses an ungranted guest import |
| Malformed request | tampering | Request bytes | high likelihood, major impact | Strict decoder: gate malformed-request acceptance vectors, replayed in the compiled guest by prismpm verify |
| Negative activation | tampering | Answer | medium likelihood, major impact | Floor at the zero point: proof MnistRequantClampProofs::inv001Holds |
| Oversized request | denialOfService | Request bytes | medium likelihood, minor impact | Bounded request: gate acceptance vectors at the request bound, one byte over it, and at the guest allocation bound, replayed by prismpm verify |
| Substituted holo | spoofing | Published holo | low likelihood, critical impact | Fingerprint and provenance: gate actions/attest-build-provenance in the pages workflow; gate prism-code check of the holo identities in the page |
| Substituted host | spoofing | Published holo | low likelihood, critical impact | accepted: A page cannot defend against its own host. The holo carries signed build provenance a visitor can check, and the app can be rebuilt from its prompt. |
| Tampered model | tampering | Model source | low likelihood, major impact | Regenerated from the prompt: gate prismpm verify in the SDK image prismpm.lock pins; review app/prompt.json |

## Quality

ISO/IEC 25010:2023 requirements. Each has a measure and a threshold that a theorem pins.

| Requirement | Characteristic | Measure | Threshold |
| --- | --- | --- | --- |
| Bounded allocation: The guest allocates at most 128 bytes for one request. | Performance efficiency: Resource utilization | Guest allocation bytes | 128 |
| Bounded request: A request over 64 bytes is refused before any field is read. | Performance efficiency: Time behaviour | Request bytes read | 64 |
| Class agrees with the authority: The package returns onnxruntime's class on every test image, as MN-05 gates. | Functional suitability: Functional appropriateness | Class disagreements | 0 |
| Codes fit uint8: Every activation code lies in 0..255. | Functional suitability: Functional correctness | Largest activation code | 255 |
| Every property proved: All 3 properties are theorems the Lean kernel checks. | Security: Integrity | Unproved properties | 0 |
| Every request answered: Every request gets an answer: a rule, passed otherwise, or invalid. | Functional suitability: Functional completeness | Unanswered requests | 0 |
| Every vector replays: All 25 acceptance vectors replay in the compiled guest, the shortest 0 bytes long. | Reliability: Faultlessness | Failed vectors | 0 |
| Examples answered as stated: Every one of the 7 examples of the spec is answered as it states. | Functional suitability: Functional correctness | Example mismatches | 0 |

## Compliance

One obligation per standard, each naming its evidence.

| Standard | Subject | Evidence |
| --- | --- | --- |
| ISO/IEC/IEEE 42010:2022 | Architecture description | Architecture::architectureDescriptionHolds |
| ISO/PAS 19450:2015 and OMG UML 2.5.1 | Design views | Design::viewOpmDecide, Design::viewUmlComponents, Design::viewUmlRequest, Design::viewUmlStates |
| ISO/IEC 25010:2023 | Product quality | Quality::qualityModelHolds |
| ISO/IEC 27034-1:2011 and ISO/IEC 27005:2022 | Application security and risk | Security::controlSet |
| OMG DMN 1.5, hit policy FIRST | Decision table | MnistRequantClamp::judge |
| OpenSpec | Requirements | MnistRequantClamp::application |
| SPDX MIT OR Apache-2.0 | Licensing | MnistRequantClamp::application |

## Rendered design views

Written by the SDK from the design records when it verified the app.

### design/Design.viewOpmDecide.opl

```
View: Design::viewOpmDecide
Title: Deciding a Requantization clamp request
Viewpoint: Architecture::viewpointModelAuditorCorrectAnswers
Notation: ISO/PAS 19450:2015 OPM, Prism OPL profile

componentBrowser is an object.
componentRequantizationClampGuest is an object.
componentRequantizationClampGuest can be stateDeciding or stateIdle.
processDecide is a process.
processEncodeAnswer is a process.
processJudge is a process.
processParseRequest is a process.
componentRequantizationClampGuest handles processDecide.
processParseRequest requires componentBrowser.
processEncodeAnswer affects componentBrowser.
processJudge invokes processEncodeAnswer.
processParseRequest invokes processJudge.
processDecide zooms into processParseRequest, processJudge, and processEncodeAnswer, in that sequence.

```

### design/Design.viewUmlComponents.puml

```
@startuml
' UML 2.5.1 component diagram
' view: Design::viewUmlComponents
' viewpoint: Architecture::viewpointVerifierIntegrityOfThePublishedApp
title Components of Requantization clamp
component "componentBrowser" as c0
component "componentGitHubPages" as c1
component "componentMnistPackage" as c2
component "componentOnnxruntime" as c3
component "componentPrismBuild" as c4
component "componentRequantizationClampGuest" as c5
component "componentRequantizationClampPage" as c6
component "componentSourceRepository" as c7
c0 --> c5 : edgeBrowserToRequantizationClampGuest
c1 --> c0 : edgeGitHubPagesToBrowser
c2 --> c5 : edgeMnistPackageToRequantizationClampGuest
c3 --> c5 : edgeOnnxruntimeToRequantizationClampGuest
c4 --> c5 : edgePrismBuildToRequantizationClampGuest
c4 --> c6 : edgePrismBuildToRequantizationClampPage
c5 --> c0 : edgeRequantizationClampGuestToBrowser
c5 --> c2 : edgeRequantizationClampGuestToMnistPackage
c5 --> c3 : edgeRequantizationClampGuestToOnnxruntime
c6 --> c1 : edgeRequantizationClampPageToGitHubPages
c7 --> c4 : edgeSourceRepositoryToPrismBuild
@enduml

```

### design/Design.viewUmlRequest.puml

```
@startuml
' UML 2.5.1 sequence diagram
' view: Design::viewUmlRequest
' viewpoint: Architecture::viewpointModelAuditorCorrectAnswers
title Answering a Requantization clamp request
participant "componentBrowser" as p0
participant "componentRequantizationClampGuest" as p1
p0 -> p1 : processDecide
p1 --> p0 : processDecide
@enduml

```

### design/Design.viewUmlStates.puml

```
@startuml
' UML 2.5.1 state machine diagram
' view: Design::viewUmlStates
' viewpoint: Architecture::viewpointPackageIntegratorRefusedMalformedRequests
title States of the Requantization clamp guest
state "stateAnsweredCeiling" as s0
state "stateAnsweredFloor" as s1
state "stateAnsweredPassed" as s2
state "stateDeciding" as s3
state "stateIdle" as s4
state "stateRefused" as s5
[*] --> s4
s4 --> s3 : processParseRequest
s4 --> s5 : processParseRequest
s3 --> s1 : processRule1
s3 --> s0 : processRule2
s3 --> s2 : processOtherwise
s1 --> s4 : processEncodeAnswer
s2 --> s4 : processEncodeAnswer
s0 --> s4 : processEncodeAnswer
s5 --> s4 : processEncodeAnswer
@enduml

```

## Prism source

Every file the builder wrote, laid out as a repository created from UOR-Foundation/template; the download prism-mnist-requant-clamp.zip has them all.

- app/src/Architecture.lex.tex (406 lines)
- app/src/Compliance.lex.tex (56 lines)
- app/src/Design.lex.tex (521 lines)
- app/src/Features.lex.tex (102 lines)
- app/src/Quality.lex.tex (375 lines)
- app/src/Security.lex.tex (551 lines)
- app/src/MnistRequantClamp.lex.tex (172 lines)
- app/src/MnistRequantClampProofs.lex.tex (90 lines)
- app/lexlean.toml (43 lines)
- app/prompt.json (283 lines)
- model/ids.toml (59 lines)
- features/suites/mnist\_requant\_clamp.feature (38 lines)
- crates/conformance/tests/mnist\_requant\_clamp.rs (122 lines)
- site/app.json (102 lines)
- openspec/specs/mnist-requant-clamp/spec.md (136 lines)
