omnius 1.0.923 → 1.0.925
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{providerRegistry.d.ts → _types/backend-vllm/providerRegistry.d.ts} +0 -1
- package/dist/_types/backend-vllm/types.d.ts +209 -0
- package/dist/_types/execution/av/media-capability.d.ts +94 -0
- package/dist/_types/execution/delegation-contract.d.ts +102 -0
- package/dist/_types/execution/evidence.d.ts +68 -0
- package/dist/_types/execution/html-source-evidence.d.ts +65 -0
- package/dist/_types/execution/mcp/types.d.ts +169 -0
- package/dist/_types/execution/mutation-contract.d.ts +102 -0
- package/dist/_types/execution/nol/artifacts.d.ts +39 -0
- package/dist/_types/execution/nol/checkpoint-edits.d.ts +98 -0
- package/dist/_types/execution/nol/distributions.d.ts +128 -0
- package/dist/_types/execution/nol/gguf-checkpoint-edits.d.ts +194 -0
- package/dist/_types/execution/nol/gguf-control-reader.d.ts +224 -0
- package/dist/_types/execution/nol/lora-exports.d.ts +129 -0
- package/dist/_types/execution/nol/neuronary.d.ts +212 -0
- package/dist/_types/execution/nol/pytorch-control-reader.d.ts +143 -0
- package/dist/_types/execution/nol/qwen35-head-sites.d.ts +61 -0
- package/dist/_types/execution/nol/worker-assets.d.ts +82 -0
- package/dist/_types/execution/nol/worker-protocol.d.ts +94 -0
- package/dist/_types/execution/page-content-source.d.ts +40 -0
- package/dist/_types/execution/rapid-computer-use/artifact-store.d.ts +21 -0
- package/dist/_types/execution/rapid-computer-use/contracts.d.ts +320 -0
- package/dist/_types/execution/rapid-computer-use/decision.d.ts +70 -0
- package/dist/_types/execution/rapid-computer-use/desktop-verification.d.ts +23 -0
- package/dist/_types/execution/rapid-computer-use/geometry.d.ts +57 -0
- package/dist/_types/execution/rapid-computer-use/planner.d.ts +78 -0
- package/dist/_types/execution/rapid-computer-use/trace.d.ts +80 -0
- package/dist/_types/execution/rapid-computer-use/visual.d.ts +48 -0
- package/dist/_types/execution/shell-runs.d.ts +78 -0
- package/dist/_types/execution/streamed-web-source.d.ts +64 -0
- package/dist/_types/execution/tools/browser-page-fallback.d.ts +25 -0
- package/dist/_types/execution/tools/network-egress-policy.d.ts +30 -0
- package/dist/_types/execution/tools/pdf-native-tables.d.ts +46 -0
- package/dist/_types/execution/tools/todo-store.d.ts +133 -0
- package/dist/_types/execution/tools/web-fetch.d.ts +57 -0
- package/dist/_types/execution/tools/workboard.d.ts +1223 -0
- package/dist/_types/execution/types.d.ts +549 -0
- package/dist/_types/execution/web-source.d.ts +14 -0
- package/dist/_types/memory/artifactReviewSourceIndex.d.ts +133 -0
- package/dist/_types/memory/contextMemoryLedger.d.ts +213 -0
- package/dist/_types/memory/db.d.ts +12 -0
- package/dist/_types/memory/embeddings.d.ts +36 -0
- package/dist/_types/memory/immutableEvidenceStore.d.ts +165 -0
- package/dist/_types/memory/memoryIngestion.d.ts +65 -0
- package/dist/_types/memory/memoryTypes.d.ts +312 -0
- package/dist/_types/memory/sourceCorpusStore.d.ts +331 -0
- package/dist/_types/memory/structuredMemoryStore.d.ts +105 -0
- package/dist/_types/memory/unifiedMemoryStore.d.ts +127 -0
- package/dist/_types/memory/virtualMemory.d.ts +187 -0
- package/dist/_types/orchestrator/agentic-page-content-receipt.d.ts +20 -0
- package/dist/_types/orchestrator/agentic-web-fetch-receipt.d.ts +20 -0
- package/dist/_types/orchestrator/agenticRunner.d.ts +5219 -0
- package/dist/_types/orchestrator/app-state.d.ts +171 -0
- package/dist/_types/orchestrator/artifactClaimCritic.d.ts +63 -0
- package/dist/_types/orchestrator/artifactQuality.d.ts +15 -0
- package/dist/_types/orchestrator/artifactSemanticIntegrity.d.ts +203 -0
- package/dist/_types/orchestrator/canonical-context-projection.d.ts +254 -0
- package/dist/_types/orchestrator/canonical-source-body-projection.d.ts +51 -0
- package/dist/_types/orchestrator/completion-review-pending.d.ts +24 -0
- package/dist/_types/orchestrator/completionContract.d.ts +103 -0
- package/dist/_types/orchestrator/completionFinalization.d.ts +224 -0
- package/dist/_types/orchestrator/completionLedger.d.ts +429 -0
- package/dist/_types/orchestrator/completionReadiness.d.ts +234 -0
- package/dist/_types/orchestrator/context-admission.d.ts +93 -0
- package/dist/_types/orchestrator/context-dump-retention.d.ts +25 -0
- package/dist/_types/orchestrator/context-fabric.d.ts +133 -0
- package/dist/_types/orchestrator/contextEngine.d.ts +68 -0
- package/dist/_types/orchestrator/contextWindowDump.d.ts +327 -0
- package/dist/_types/orchestrator/convergence-breaker.d.ts +225 -0
- package/dist/_types/orchestrator/convergence-progress.d.ts +66 -0
- package/dist/_types/orchestrator/deliveryCoverage.d.ts +181 -0
- package/dist/_types/orchestrator/document-persistence-goal-binding.d.ts +106 -0
- package/dist/_types/orchestrator/durable-document-worker.d.ts +85 -0
- package/dist/_types/orchestrator/evidenceBranch.d.ts +291 -0
- package/dist/_types/orchestrator/expected-inference-response.d.ts +55 -0
- package/dist/_types/orchestrator/expectedOutcomeContract.d.ts +58 -0
- package/dist/_types/orchestrator/failure-taxonomy.d.ts +36 -0
- package/dist/_types/orchestrator/focusSupervisor.d.ts +436 -0
- package/dist/_types/orchestrator/forced-update-requirement-recovery.d.ts +105 -0
- package/dist/_types/orchestrator/hooks.d.ts +100 -0
- package/dist/_types/orchestrator/inference-pressure.d.ts +61 -0
- package/dist/_types/orchestrator/integrationClosure.d.ts +89 -0
- package/dist/_types/orchestrator/interruption-lifecycle.d.ts +154 -0
- package/dist/_types/orchestrator/live-memory-passages.d.ts +51 -0
- package/dist/_types/orchestrator/liveVirtualContext.d.ts +84 -0
- package/dist/_types/orchestrator/memory-compiler.d.ts +254 -0
- package/dist/_types/orchestrator/memory-consolidation.d.ts +134 -0
- package/dist/_types/orchestrator/model-router.d.ts +17 -0
- package/dist/_types/orchestrator/modelResponseDiagnostics.d.ts +71 -0
- package/dist/_types/orchestrator/nativeRequirementAmendment.d.ts +63 -0
- package/dist/_types/orchestrator/nol/coordinator.d.ts +204 -0
- package/dist/_types/orchestrator/nol/datasets.d.ts +58 -0
- package/dist/_types/orchestrator/nol/discovery.d.ts +286 -0
- package/dist/_types/orchestrator/nol/evaluation.d.ts +59 -0
- package/dist/_types/orchestrator/nol/model-validation.d.ts +198 -0
- package/dist/_types/orchestrator/nol/statistics.d.ts +142 -0
- package/dist/_types/orchestrator/nol/store.d.ts +133 -0
- package/dist/_types/orchestrator/nol/variant-registry.d.ts +292 -0
- package/dist/_types/orchestrator/ollama-context-policy.d.ts +34 -0
- package/dist/_types/orchestrator/personality.d.ts +66 -0
- package/dist/_types/orchestrator/prompt-cache.d.ts +24 -0
- package/dist/_types/orchestrator/remote-inference-fallback.d.ts +224 -0
- package/dist/_types/orchestrator/remote-inference-policy.d.ts +58 -0
- package/dist/_types/orchestrator/request-budget.d.ts +75 -0
- package/dist/_types/orchestrator/requirementCoverage.d.ts +69 -0
- package/dist/_types/orchestrator/reviewedInterpretation.d.ts +111 -0
- package/dist/_types/orchestrator/runEvents.d.ts +115 -0
- package/dist/_types/orchestrator/runtime-rollout.d.ts +63 -0
- package/dist/_types/orchestrator/semanticVerification.d.ts +135 -0
- package/dist/_types/orchestrator/source-wide-extraction.d.ts +202 -0
- package/dist/_types/orchestrator/steeringIntake.d.ts +123 -0
- package/dist/_types/orchestrator/structured-memory-extraction-worker.d.ts +89 -0
- package/dist/_types/orchestrator/structuredMemoryInference.d.ts +62 -0
- package/dist/_types/orchestrator/successful-procedure-memory.d.ts +127 -0
- package/dist/_types/orchestrator/supportedAnswer.d.ts +68 -0
- package/dist/_types/orchestrator/taskEffectEvidence.d.ts +38 -0
- package/dist/_types/orchestrator/taskExecutionSnapshot.d.ts +67 -0
- package/dist/_types/orchestrator/taskObjective.d.ts +310 -0
- package/dist/_types/orchestrator/taskObjectiveContinuation.d.ts +134 -0
- package/dist/_types/orchestrator/taskRequirementReview.d.ts +246 -0
- package/dist/_types/orchestrator/taskRequirements.d.ts +80 -0
- package/dist/_types/orchestrator/taskSemanticAdmission.d.ts +159 -0
- package/dist/_types/orchestrator/taskWorkDelegation.d.ts +147 -0
- package/dist/_types/orchestrator/taskWorkPlan.d.ts +177 -0
- package/dist/_types/orchestrator/telegram-passive-history.d.ts +42 -0
- package/dist/_types/orchestrator/terminalTaskReport.d.ts +91 -0
- package/dist/_types/orchestrator/todoObservability.d.ts +147 -0
- package/dist/_types/orchestrator/tool-exposure-policy.d.ts +100 -0
- package/dist/_types/orchestrator/trajectory-checkpoint.d.ts +159 -0
- package/dist/_types/orchestrator/types.d.ts +185 -0
- package/dist/_types/schemas/dispatch.d.ts +53 -0
- package/dist/_types/schemas/feature-workflow.d.ts +362 -0
- package/dist/_types/schemas/messages.d.ts +15 -0
- package/dist/_types/schemas/nol-assets.d.ts +955 -0
- package/dist/_types/schemas/nol-json.d.ts +2 -0
- package/dist/_types/schemas/nol.d.ts +3995 -0
- package/dist/_types/schemas/patch.d.ts +47 -0
- package/dist/_types/schemas/plan.d.ts +47 -0
- package/dist/_types/schemas/repoProfile.d.ts +116 -0
- package/dist/_types/schemas/retrieval.d.ts +44 -0
- package/dist/_types/schemas/task.d.ts +57 -0
- package/dist/_types/schemas/tools.d.ts +16 -0
- package/dist/_types/schemas/verification.d.ts +31 -0
- package/dist/api/py-embed.js +3353 -1829
- package/dist/assets/nol-checkpoint-editor.py +701 -0
- package/dist/assets/nol-gguf-checkpoint-editor.py +785 -0
- package/dist/assets/nol-gguf-control-reader.py +428 -0
- package/dist/assets/nol-gne-tools-worker.py +425 -0
- package/dist/assets/nol-gne-worker.py +1081 -0
- package/dist/assets/nol-lora-exporter.py +349 -0
- package/dist/assets/nol-pytorch-control-reader.py +470 -0
- package/dist/assets/nol-transformers-nnsight-worker.py +512 -0
- package/dist/assets/nol-transformers-peft-validation-worker.py +385 -0
- package/dist/assets/nol-transformers-peft-worker.py +488 -0
- package/dist/assets/nol-transformers-research-worker.py +472 -0
- package/dist/assets/nol-transformers-worker.py +920 -0
- package/dist/assets/nol-vllm-owned-worker.py +803 -0
- package/dist/assets/nol-vllm-runtime.py +695 -0
- package/dist/assets/nol-vllm-tokenizer.py +93 -0
- package/dist/assets/nol-vllm-worker.py +201 -0
- package/dist/computer-use/configured-planner.d.ts +37 -0
- package/dist/computer-use/configured-point.d.ts +35 -0
- package/dist/computer-use/host-session.d.ts +60 -0
- package/dist/computer-use/runner-ui-port.d.ts +37 -0
- package/dist/computer-use/session-review.d.ts +14 -0
- package/dist/computer-use/task-spec.d.ts +84 -0
- package/dist/discovery.d.ts +16 -2
- package/dist/index.js +2 -2
- package/dist/library.d.ts +94 -10
- package/dist/library.js +144003 -87414
- package/dist/memory-maintenance-worker.js +1676 -511
- package/dist/nol/cpu-control-reader-profile.d.ts +93 -0
- package/dist/nol/cpu-control-reader-service.d.ts +87 -0
- package/dist/nol/cuda-lease.d.ts +111 -0
- package/dist/nol/cuda-mutations.d.ts +34 -0
- package/dist/nol/export-runtime-config.d.ts +114 -0
- package/dist/nol/export-service.d.ts +143 -0
- package/dist/nol/facade.d.ts +147 -0
- package/dist/nol/gguf-cpu-control-reader-profile.d.ts +106 -0
- package/dist/nol/gguf-cpu-control-reader-service.d.ts +91 -0
- package/dist/nol/gguf-model-control-verifier.d.ts +120 -0
- package/dist/nol/gguf-parameter-inventory.d.ts +28 -0
- package/dist/nol/gne-adapter.d.ts +134 -0
- package/dist/nol/gne-agent-evaluation.d.ts +84 -0
- package/dist/nol/gne-profile.d.ts +124 -0
- package/dist/nol/gne-tools-profile.d.ts +148 -0
- package/dist/nol/gne-tools-transport.d.ts +194 -0
- package/dist/nol/model-actions.d.ts +662 -0
- package/dist/nol/model-control-verifier.d.ts +135 -0
- package/dist/nol/model-json-scorer.d.ts +13 -0
- package/dist/nol/model-runtime-config.d.ts +830 -0
- package/dist/nol/model-serving.d.ts +130 -0
- package/dist/nol/model-subject-adapter.d.ts +72 -0
- package/dist/nol/model-validation-factory.d.ts +113 -0
- package/dist/nol/neuronary-catalog.d.ts +130 -0
- package/dist/nol/orphan-custody.d.ts +72 -0
- package/dist/nol/peft-conformance.d.ts +48 -0
- package/dist/nol/peft-control-types.d.ts +137 -0
- package/dist/nol/peft-control-verifier.d.ts +8 -0
- package/dist/nol/peft-model-actions.d.ts +41 -0
- package/dist/nol/peft-model-authority.d.ts +146 -0
- package/dist/nol/peft-model-controls.d.ts +20 -0
- package/dist/nol/peft-model-host.d.ts +47 -0
- package/dist/nol/peft-model-profile.d.ts +161 -0
- package/dist/nol/peft-model-runtime-config.d.ts +174 -0
- package/dist/nol/peft-model-subject-adapter.d.ts +36 -0
- package/dist/nol/peft-validation.d.ts +105 -0
- package/dist/nol/persistent-parameter-inventory.d.ts +32 -0
- package/dist/nol/runtime.d.ts +100 -0
- package/dist/nol/sqlite-store.d.ts +80 -0
- package/dist/nol/transformers-adapter.d.ts +119 -0
- package/dist/nol/transformers-nnsight.d.ts +87 -0
- package/dist/nol/transformers-peft.d.ts +107 -0
- package/dist/nol/transformers-research.d.ts +114 -0
- package/dist/nol/variant-service.d.ts +143 -0
- package/dist/nol/variant-store.d.ts +51 -0
- package/dist/nol/vllm-actions.d.ts +774 -0
- package/dist/nol/vllm-adapter.d.ts +1473 -0
- package/dist/nol/vllm-authority.d.ts +55 -0
- package/dist/nol/vllm-conformance.d.ts +662 -0
- package/dist/nol/vllm-profile.d.ts +850 -0
- package/dist/nol/vllm-protocol.d.ts +1505 -0
- package/dist/nol/vllm-runtime-config.d.ts +120 -0
- package/dist/nol/vllm-runtime.d.ts +34 -0
- package/dist/nol/vllm-startup.d.ts +235 -0
- package/dist/omni-setup-worker.js +3433 -1909
- package/dist/service-version.d.ts +0 -1
- package/dist/tui/async-process.d.ts +27 -0
- package/dist/tui/native/worker.js +3 -1
- package/dist/tui/telegram-action-session-registry.d.ts +136 -0
- package/dist/tui/telegram-cognition-queue.d.ts +154 -0
- package/dist/tui/telegram-context-packet-v2.d.ts +99 -0
- package/dist/tui/telegram-input-ownership.d.ts +78 -0
- package/dist/tui/telegram-turn-contract-v2.d.ts +62 -0
- package/dist/update-worker-runtime.js +4216 -2603
- package/docs/DISCOVERY.json +389 -0
- package/docs/DISCOVERY.md +4 -0
- package/npm-shrinkwrap.json +28 -12
- package/package.json +3 -2
|
@@ -0,0 +1,1081 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Job-owned NOL compute worker. Stdlib-only until an explicit zero-token load.
|
|
3
|
+
|
|
4
|
+
Transport: uint32 big-endian UTF-8 JSON frames. Stdout is never a log stream.
|
|
5
|
+
The host owns GPU leasing, artifact publication, native receipts and grading.
|
|
6
|
+
This process reports observed facts; it cannot attest broker custody by itself.
|
|
7
|
+
"""
|
|
8
|
+
import contextlib
|
|
9
|
+
from decimal import Decimal
|
|
10
|
+
import gc
|
|
11
|
+
import hashlib
|
|
12
|
+
import importlib.metadata
|
|
13
|
+
import io
|
|
14
|
+
import json
|
|
15
|
+
import math
|
|
16
|
+
import os
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
import re
|
|
19
|
+
import struct
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
import tempfile
|
|
23
|
+
|
|
24
|
+
PROTOCOL = "omnius.nol.worker.v1"
|
|
25
|
+
WORKER_VERSION = "omnius.nol.gne.v1"
|
|
26
|
+
MAX_FRAME = int(os.environ.get("OMNIUS_NOL_MAX_FRAME_BYTES", "1048576"))
|
|
27
|
+
WIRE_OUT = sys.stdout.buffer
|
|
28
|
+
OWNER = {"sessionId": os.environ.get("OMNIUS_NOL_WORKER_SESSION", ""),
|
|
29
|
+
"jobId": os.environ.get("OMNIUS_NOL_JOB_ID", ""),
|
|
30
|
+
"ownerId": os.environ.get("OMNIUS_NOL_OWNER_ID", ""),
|
|
31
|
+
"generation": int(os.environ.get("OMNIUS_NOL_GENERATION", "0"))}
|
|
32
|
+
UUID = re.compile(r"^GPU-[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
|
|
33
|
+
SHA = re.compile(r"^[a-f0-9]{64}$")
|
|
34
|
+
RUNTIME_OPS = {"NEURON_ADD", "NEURON_GAIN"}
|
|
35
|
+
GNE_REVISION = "b1ded91bf1ebd903f7229e4969cc764a418336a8"
|
|
36
|
+
NATIVE_CODE = re.compile(r"\.(?:py|pyd|dll|dylib|ptx|cubin)$|\.so(?:\.\d+)*$", re.IGNORECASE)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Rejected(Exception):
|
|
40
|
+
def __init__(self, code, message, fatal=False):
|
|
41
|
+
super().__init__(message)
|
|
42
|
+
self.code, self.fatal = code, fatal
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def require(condition, message, code="INVALID_REQUEST"):
|
|
46
|
+
if not condition:
|
|
47
|
+
raise Rejected(code, message)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def fields(value, required, optional=()):
|
|
51
|
+
require(type(value) is dict and set(required) <= value.keys() and not (value.keys() - set(required) - set(optional)), "Unknown or missing fields")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def integer(value, minimum=0, maximum=9007199254740991):
|
|
55
|
+
require(type(value) is int and minimum <= value <= maximum, "Invalid bounded integer")
|
|
56
|
+
return value
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def number(value):
|
|
60
|
+
require(type(value) in (int, float) and math.isfinite(value), "Nonfinite numeric value")
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def unique_object(pairs):
|
|
65
|
+
out = {}
|
|
66
|
+
for key, value in pairs:
|
|
67
|
+
require(key not in out, "Duplicate JSON object property")
|
|
68
|
+
out[key] = value
|
|
69
|
+
return out
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def parse_json(raw):
|
|
73
|
+
return json.loads(raw, object_pairs_hook=unique_object,
|
|
74
|
+
parse_int=lambda text: -0.0 if text == "-0" else int(text),
|
|
75
|
+
parse_constant=lambda _: (_ for _ in ()).throw(Rejected("INVALID_JSON", "Nonfinite JSON number")))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def canonical_simple(value):
|
|
79
|
+
"""Only used for runtime/file inventories containing strings and integers.
|
|
80
|
+
Scientific records arrive with their exact host-canonical identity bodies.
|
|
81
|
+
"""
|
|
82
|
+
return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def digest_bytes(value):
|
|
86
|
+
return hashlib.sha256(value).hexdigest()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def hash_file(path, maximum=None):
|
|
90
|
+
path = Path(path)
|
|
91
|
+
require(path.is_file() and not path.is_symlink(), "Input must be a regular nonsymlink file")
|
|
92
|
+
before = path.stat()
|
|
93
|
+
require(maximum is None or before.st_size <= maximum, "File byte budget exceeded", "CAPACITY")
|
|
94
|
+
h, size = hashlib.sha256(), 0
|
|
95
|
+
with path.open("rb") as stream:
|
|
96
|
+
opened = os.fstat(stream.fileno())
|
|
97
|
+
require((opened.st_dev, opened.st_ino) == (before.st_dev, before.st_ino), "File identity changed")
|
|
98
|
+
while True:
|
|
99
|
+
block = stream.read(1024 * 1024)
|
|
100
|
+
if not block:
|
|
101
|
+
break
|
|
102
|
+
h.update(block)
|
|
103
|
+
size += len(block)
|
|
104
|
+
require(size <= before.st_size and (maximum is None or size <= maximum), "File grew beyond its frozen byte bound", "CAPACITY")
|
|
105
|
+
after = os.fstat(stream.fileno())
|
|
106
|
+
require((before.st_size, before.st_mtime_ns, before.st_ctime_ns) ==
|
|
107
|
+
(size, after.st_mtime_ns, after.st_ctime_ns), "File changed while hashing")
|
|
108
|
+
return {"sha256": h.hexdigest(), "sizeBytes": size}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def safe_path(root, relative):
|
|
112
|
+
require(type(relative) is str and relative and not relative.startswith("/") and "\\" not in relative and "\0" not in relative,
|
|
113
|
+
"Invalid relative file path")
|
|
114
|
+
require(all(part not in ("", ".", "..") for part in relative.split("/")), "Invalid relative path component")
|
|
115
|
+
root = Path(root).resolve(strict=True)
|
|
116
|
+
current = root
|
|
117
|
+
for part in relative.split("/"):
|
|
118
|
+
current = current / part
|
|
119
|
+
require(not current.is_symlink(), "Symlinks are not accepted in frozen input paths")
|
|
120
|
+
require(current.resolve(strict=True).is_relative_to(root), "Input escaped its frozen root")
|
|
121
|
+
return current
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def same_json(left, right):
|
|
125
|
+
if type(left) in (int, float) and type(right) in (int, float):
|
|
126
|
+
return left == right and (left != 0 or math.copysign(1, left) == math.copysign(1, right))
|
|
127
|
+
if type(left) is not type(right):
|
|
128
|
+
return False
|
|
129
|
+
if type(left) is dict:
|
|
130
|
+
return left.keys() == right.keys() and all(same_json(left[key], right[key]) for key in left)
|
|
131
|
+
if type(left) is list:
|
|
132
|
+
return len(left) == len(right) and all(same_json(a, b) for a, b in zip(left, right))
|
|
133
|
+
return left == right
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def verify_identity(raw, expected, expected_hash):
|
|
137
|
+
require(type(raw) is str and SHA.fullmatch(expected_hash or ""), "Missing exact identity body")
|
|
138
|
+
require(digest_bytes(raw.encode("utf-8")) == expected_hash and same_json(parse_json(raw), expected), "Frozen identity digest/body mismatch", "IDENTITY")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def runtime_info(lock_path=None, hash_runtime=False, max_bytes=34359738368):
|
|
142
|
+
packages, code = {}, []
|
|
143
|
+
spent = 0
|
|
144
|
+
for distribution in sorted(importlib.metadata.distributions(), key=lambda item: item.metadata.get("Name", "").lower()):
|
|
145
|
+
name = distribution.metadata.get("Name", "")
|
|
146
|
+
if not name:
|
|
147
|
+
continue
|
|
148
|
+
packages[name] = distribution.version
|
|
149
|
+
if hash_runtime:
|
|
150
|
+
entries = []
|
|
151
|
+
for relative in sorted(distribution.files or [], key=str):
|
|
152
|
+
if not NATIVE_CODE.search(str(relative)):
|
|
153
|
+
continue
|
|
154
|
+
path = Path(distribution.locate_file(relative))
|
|
155
|
+
# Symlinked libraries are rejected rather than silently hashing
|
|
156
|
+
# a different native installation than the isolated runtime.
|
|
157
|
+
actual = hash_file(path, max_bytes - spent)
|
|
158
|
+
spent += actual["sizeBytes"]
|
|
159
|
+
entries.append({"path": str(relative), **actual})
|
|
160
|
+
code.append({"name": name, "digest": digest_bytes(canonical_simple(entries).encode()), "files": len(entries)})
|
|
161
|
+
info = {"schema": "omnius.nol.gne-build.v1", "workerVersion": WORKER_VERSION,
|
|
162
|
+
"workerSha256": hash_file(Path(__file__).resolve())["sha256"], "pythonVersion": sys.version.split()[0],
|
|
163
|
+
"packages": packages, "packageCode": code,
|
|
164
|
+
"pythonExecutableSha256": hash_file(Path(sys.executable).resolve())["sha256"]}
|
|
165
|
+
if lock_path:
|
|
166
|
+
info["dependencyLockDigest"] = hash_file(lock_path, 1048576)["sha256"]
|
|
167
|
+
return info
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def placement(uuid):
|
|
171
|
+
rows = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,gpu_uuid,used_memory", "--format=csv,noheader,nounits"],
|
|
172
|
+
check=True, capture_output=True, timeout=10, text=True)
|
|
173
|
+
require(len(rows.stdout.encode()) <= 1048576, "Placement inventory exceeds its byte bound")
|
|
174
|
+
resident = [row.split(",") for row in rows.stdout.splitlines() if row.split(",")[0].strip() == str(os.getpid())]
|
|
175
|
+
require(resident and all(row[1].strip() == uuid and float(row[2].strip()) > 0 for row in resident), "Actual CUDA residency differs from the reserved UUID", "PLACEMENT")
|
|
176
|
+
stat = Path(f"/proc/{os.getpid()}/stat").read_text()
|
|
177
|
+
return {"pid": os.getpid(), "gpuUuid": uuid, "startIdentity": stat[stat.rfind(")") + 2:].split()[19]}
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def canonical_gguf(value):
|
|
182
|
+
"""Canonical JSON of GGUF tokenizer metadata, including float32 scores.
|
|
183
|
+
Numeric formatting follows the host's finite binary64 JSON convention;
|
|
184
|
+
scientific record identities still use exact host-canonical bodies.
|
|
185
|
+
"""
|
|
186
|
+
if value is None:
|
|
187
|
+
return "null"
|
|
188
|
+
if type(value) is bool:
|
|
189
|
+
return "true" if value else "false"
|
|
190
|
+
if type(value) is str:
|
|
191
|
+
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
|
192
|
+
if type(value) in (int, float):
|
|
193
|
+
number(value)
|
|
194
|
+
if value == 0:
|
|
195
|
+
return "-0" if math.copysign(1, value) < 0 else "0"
|
|
196
|
+
if type(value) is int:
|
|
197
|
+
require(abs(value) < 1e21 and int(float(value)) == value, "GGUF integer cannot be represented exactly by the host JSON identity", "IDENTITY")
|
|
198
|
+
return str(value)
|
|
199
|
+
text = repr(value).lower()
|
|
200
|
+
if 0.000001 <= abs(value) < 1e21:
|
|
201
|
+
return format(Decimal(text), "f").rstrip("0").rstrip(".") if "." in format(Decimal(text), "f") else format(Decimal(text), "f")
|
|
202
|
+
mantissa, exponent = text.split("e") if "e" in text else (text, "0")
|
|
203
|
+
mantissa = mantissa.rstrip("0").rstrip(".") if "." in mantissa else mantissa
|
|
204
|
+
exponent = int(exponent)
|
|
205
|
+
return mantissa + "e" + ("+" if exponent >= 0 else "-") + str(abs(exponent))
|
|
206
|
+
if type(value) is list:
|
|
207
|
+
return "[" + ",".join(canonical_gguf(item) for item in value) + "]"
|
|
208
|
+
require(type(value) is dict, "Unsupported GGUF metadata value")
|
|
209
|
+
keys = sorted(value, key=lambda key: key.encode("utf-16-be", "surrogatepass"))
|
|
210
|
+
return "{" + ",".join(canonical_gguf(key) + ":" + canonical_gguf(value[key]) for key in keys) + "}"
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def gguf_metadata(path):
|
|
214
|
+
"""Read bounded metadata only. No GNE import, mmap, CUDA or generation."""
|
|
215
|
+
budget = 64 * 1024 * 1024
|
|
216
|
+
with Path(path).open("rb") as stream:
|
|
217
|
+
def take(count):
|
|
218
|
+
require(0 <= count <= budget and stream.tell() + count <= budget, "GGUF metadata byte bound exceeded", "CAPACITY")
|
|
219
|
+
data = stream.read(count)
|
|
220
|
+
require(len(data) == count, "Truncated GGUF metadata", "IDENTITY")
|
|
221
|
+
return data
|
|
222
|
+
def unpack(fmt):
|
|
223
|
+
return struct.unpack("<" + fmt, take(struct.calcsize("<" + fmt)))[0]
|
|
224
|
+
def string():
|
|
225
|
+
return take(unpack("Q")).decode("utf-8", "strict")
|
|
226
|
+
def value(kind, depth=0):
|
|
227
|
+
formats = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "?", 10: "Q", 11: "q", 12: "d"}
|
|
228
|
+
if kind == 8:
|
|
229
|
+
return string()
|
|
230
|
+
if kind == 9:
|
|
231
|
+
require(depth < 2, "Nested GGUF metadata exceeds bound")
|
|
232
|
+
item_kind, count = unpack("I"), unpack("Q")
|
|
233
|
+
integer(count, 0, 2000000)
|
|
234
|
+
return [value(item_kind, depth + 1) for _ in range(count)]
|
|
235
|
+
require(kind in formats, "Unknown GGUF metadata type")
|
|
236
|
+
result = unpack(formats[kind])
|
|
237
|
+
if type(result) in (int, float):
|
|
238
|
+
number(result)
|
|
239
|
+
return result
|
|
240
|
+
require(take(4) == b"GGUF" and unpack("I") in (2, 3), "Unsupported GGUF header", "IDENTITY")
|
|
241
|
+
tensors, count = unpack("Q"), unpack("Q")
|
|
242
|
+
integer(tensors, 1, 1000000)
|
|
243
|
+
integer(count, 1, 1000000)
|
|
244
|
+
metadata = {}
|
|
245
|
+
for _ in range(count):
|
|
246
|
+
key = string()
|
|
247
|
+
require(key not in metadata, "Duplicate GGUF metadata field")
|
|
248
|
+
metadata[key] = value(unpack("I"))
|
|
249
|
+
dense, reserved = {}, set()
|
|
250
|
+
for _ in range(tensors):
|
|
251
|
+
name, dimensions = string(), unpack("I")
|
|
252
|
+
require(name and dimensions <= 4, "Invalid GGUF tensor descriptor", "IDENTITY")
|
|
253
|
+
for _ in range(dimensions): integer(unpack("Q"), 1)
|
|
254
|
+
unpack("I"); unpack("Q")
|
|
255
|
+
match = re.fullmatch(r"blk\.(\d+)\.(ffn_gate|ffn_up|ffn_down)\.weight", name)
|
|
256
|
+
if match: dense.setdefault(int(match[1]), set()).add(match[2])
|
|
257
|
+
match = re.match(r"blk\.(\d+)\.nextn\.", name)
|
|
258
|
+
if match: reserved.add(int(match[1]))
|
|
259
|
+
arch = metadata.get("general.architecture")
|
|
260
|
+
require(type(arch) is str and arch, "GGUF architecture missing", "IDENTITY")
|
|
261
|
+
tokenizer = {key: item for key, item in metadata.items() if key.startswith("tokenizer.") and not key.startswith("tokenizer.chat_template")}
|
|
262
|
+
require(tokenizer and type(metadata.get("tokenizer.chat_template")) is str, "GGUF tokenizer/template metadata missing", "IDENTITY")
|
|
263
|
+
layers = integer(metadata.get(arch + ".block_count"), 1)
|
|
264
|
+
editable = sorted(layer for layer, names in dense.items() if names == {"ffn_gate", "ffn_up", "ffn_down"} and layer not in reserved)
|
|
265
|
+
return {"metadata": metadata, "tokenizer": tokenizer, "template": metadata["tokenizer.chat_template"], "architecture": arch,
|
|
266
|
+
"denseMlpLayers": editable, "unsupportedLayers": sorted(set(range(layers)) - set(editable)), "reservedLayers": sorted(reserved)}
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def gguf_column_norms(path, requested, limits, expected_file, metadata):
|
|
270
|
+
"""Explicit CPU-only dequantization. Never import GNE, llama_cpp or torch."""
|
|
271
|
+
fields(limits, ("maxWorkingBytes", "maxTensorBytes", "maxMultiplyAdds"))
|
|
272
|
+
bounds = {key: integer(value, 1) for key, value in limits.items()}
|
|
273
|
+
fields(expected_file, ("sha256", "sizeBytes"))
|
|
274
|
+
require(SHA.fullmatch(expected_file["sha256"]), "Full checkpoint identity required", "IDENTITY")
|
|
275
|
+
integer(expected_file["sizeBytes"], 1)
|
|
276
|
+
require(type(requested) is list and 0 < len(requested) <= 64, "CPU column inventory exceeds its explicit bound", "CAPACITY")
|
|
277
|
+
before = Path(path).stat()
|
|
278
|
+
require(hash_file(path) == expected_file, "CPU column checkpoint differs from its complete frozen file identity", "IDENTITY")
|
|
279
|
+
native_before = {name for name in sys.modules if name.split(".")[0] in ("gne", "llama_cpp", "torch")}
|
|
280
|
+
import numpy as np
|
|
281
|
+
from gguf import GGUFReader, GGMLQuantizationType
|
|
282
|
+
from gguf import quants
|
|
283
|
+
require({name for name in sys.modules if name.split(".")[0] in ("gne", "llama_cpp", "torch")} == native_before,
|
|
284
|
+
"CPU column reader imported a native/model runtime", "IDENTITY")
|
|
285
|
+
reader = GGUFReader(str(path), "r")
|
|
286
|
+
tensors = {tensor.name: tensor for tensor in reader.tensors}
|
|
287
|
+
require(len(tensors) == len(reader.tensors), "Duplicate GGUF tensor names", "IDENTITY")
|
|
288
|
+
coordinates, planned, capture_bytes, arithmetic = set(), {}, 0, 0
|
|
289
|
+
for item in requested:
|
|
290
|
+
fields(item, ("layer", "neuron"))
|
|
291
|
+
layer = integer(item["layer"])
|
|
292
|
+
require(layer in metadata["denseMlpLayers"], "CPU column is not a supported dense normal decoder layer", "UNSUPPORTED")
|
|
293
|
+
tensor = tensors.get(f"blk.{layer}.ffn_down.weight")
|
|
294
|
+
require(tensor is not None and len(tensor.shape) == 2, "CPU down matrix is missing or not rank two", "IDENTITY")
|
|
295
|
+
width, hidden = [integer(int(value), 1) for value in tensor.shape]
|
|
296
|
+
neuron = integer(item["neuron"], 0, width - 1)
|
|
297
|
+
require((layer, neuron) not in coordinates, "Duplicate CPU column coordinate")
|
|
298
|
+
coordinates.add((layer, neuron))
|
|
299
|
+
matrix_bytes = width * hidden * 4
|
|
300
|
+
require(matrix_bytes * 4 + len(requested) * hidden * 16 <= bounds["maxWorkingBytes"], "CPU full down-matrix dequantization exceeds working-memory admission", "CAPACITY")
|
|
301
|
+
capture_bytes += hidden * 8
|
|
302
|
+
if layer not in planned: arithmetic += width * hidden * 4
|
|
303
|
+
planned.setdefault(layer, {"tensor": tensor, "width": width, "hidden": hidden, "neurons": []})["neurons"].append(neuron)
|
|
304
|
+
require(capture_bytes <= bounds["maxTensorBytes"] and arithmetic <= bounds["maxMultiplyAdds"], "CPU column capture/arithmetic exceeds admission", "CAPACITY")
|
|
305
|
+
def decode(tensor):
|
|
306
|
+
qtype = tensor.tensor_type
|
|
307
|
+
if qtype == GGMLQuantizationType.F32:
|
|
308
|
+
return np.asarray(tensor.data, dtype=np.float32)
|
|
309
|
+
if qtype == GGMLQuantizationType.F16:
|
|
310
|
+
return np.asarray(tensor.data).astype(np.float32)
|
|
311
|
+
require(qtype in quants._type_traits, "GGUF column quantization is unsupported by the pinned pure CPU reader", "UNSUPPORTED")
|
|
312
|
+
return quants.dequantize(tensor.data, qtype).astype(np.float32, copy=False)
|
|
313
|
+
columns = []
|
|
314
|
+
for layer, plan in planned.items():
|
|
315
|
+
matrix = decode(plan["tensor"])
|
|
316
|
+
require(tuple(matrix.shape) == (plan["hidden"], plan["width"]), "GGUF dequantized matrix orientation/shape differs from frozen descriptor", "IDENTITY")
|
|
317
|
+
scale_tensor = tensors.get(f"blk.{layer}.ffn_down.scale")
|
|
318
|
+
if scale_tensor is None:
|
|
319
|
+
scale = 1.0
|
|
320
|
+
else:
|
|
321
|
+
require(math.prod(int(value) for value in scale_tensor.shape) == 1 and int(scale_tensor.data.nbytes) <= 1024,
|
|
322
|
+
"Down scaling tensor must contain one bounded scalar", "IDENTITY")
|
|
323
|
+
scale = number(float(decode(scale_tensor).reshape(-1)[0]))
|
|
324
|
+
require(scale != 0, "Zero down scale cannot define a norm-matched intervention", "UNSUPPORTED")
|
|
325
|
+
for neuron in plan["neurons"]:
|
|
326
|
+
values = [number(float(matrix[row, neuron])) for row in range(plan["hidden"])]
|
|
327
|
+
norm = math.sqrt(math.fsum(value * value for value in values))
|
|
328
|
+
require(math.isfinite(norm) and norm > 0, "Zero/nonfinite CPU down column cannot define norm matching", "UNSUPPORTED")
|
|
329
|
+
columns.append({"layer": layer, "neuron": neuron, "columnL2": norm, "ffnDownScale": scale,
|
|
330
|
+
"effectiveColumnL2": abs(scale) * norm, "shape": [plan["hidden"], plan["width"]],
|
|
331
|
+
"quantization": plan["tensor"].tensor_type.name})
|
|
332
|
+
del matrix
|
|
333
|
+
after = Path(path).stat()
|
|
334
|
+
require((before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns) ==
|
|
335
|
+
(after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns), "Checkpoint changed during CPU column inspection", "IDENTITY")
|
|
336
|
+
return {"schema": "omnius.nol.gguf-column-norms.v1", "file": expected_file, "columns": columns,
|
|
337
|
+
"normSpace": "float64_l2_of_float32_dequantized_ffn_down_column_times_native_down_scale",
|
|
338
|
+
"modelLoaded": False, "sampledTokens": 0, "nativeRuntimeImported": False}
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def pinned_source(root):
|
|
342
|
+
root = Path(root).resolve(strict=True)
|
|
343
|
+
def git(*args):
|
|
344
|
+
return subprocess.run(["git", "-C", str(root), *args], check=True, capture_output=True, timeout=10).stdout
|
|
345
|
+
require(git("rev-parse", "HEAD").decode().strip() == GNE_REVISION, "GNE revision differs from the pinned implementation", "IDENTITY")
|
|
346
|
+
require(not git("status", "--porcelain", "--untracked-files=all", "--", "gne", "configs", "pyproject.toml").strip(), "GNE implementation/configuration is modified", "IDENTITY")
|
|
347
|
+
entries = []
|
|
348
|
+
for raw in git("ls-files", "-z", "--", "gne", "configs", "pyproject.toml").split(b"\0"):
|
|
349
|
+
if raw:
|
|
350
|
+
relative = raw.decode("utf-8", "strict")
|
|
351
|
+
entries.append({"path": relative, **hash_file(safe_path(root, relative), 67108864)})
|
|
352
|
+
require(any(row["path"] == "gne/api.py" for row in entries), "Pinned GNE source is incomplete", "IDENTITY")
|
|
353
|
+
# This pinned tree has no template YAML overrides. An external GNE_CONFIGS
|
|
354
|
+
# directory must never silently change the renderer chosen by the binding.
|
|
355
|
+
require(not list((root / "configs" / "templates").glob("*.yaml")), "Renderer overrides need a separately frozen implementation", "UNSUPPORTED")
|
|
356
|
+
return {"revision": GNE_REVISION, "sourceDigest": digest_bytes(canonical_simple(entries).encode()), "files": len(entries)}
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def renderer_facts(metadata):
|
|
360
|
+
digest = digest_bytes(metadata["template"].encode("utf-8"))
|
|
361
|
+
return {"metadataChatTemplateDigest": digest, "effectiveChatTemplateDigest": digest, "overridden": False,
|
|
362
|
+
"thinking": False, "addGenerationPrompt": True}
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def gne_build(root, lock_path, hash_runtime, metadata=None, max_bytes=34359738368):
|
|
366
|
+
result = runtime_info(lock_path, hash_runtime, max_bytes)
|
|
367
|
+
result["gne"] = pinned_source(root)
|
|
368
|
+
if metadata is not None:
|
|
369
|
+
result["renderer"] = renderer_facts(metadata)
|
|
370
|
+
return result
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def isolate_gne_imports(root, scratch):
|
|
374
|
+
require(not any(name == "gne" or name.startswith("gne.") for name in sys.modules), "GNE was imported before the pinned load boundary", "IDENTITY")
|
|
375
|
+
cache = Path(scratch) / "private-bytecode"
|
|
376
|
+
cache.mkdir(mode=0o700)
|
|
377
|
+
# Ignored repository/package .pyc files are not covered by source hashes.
|
|
378
|
+
# Import from an empty private cache namespace and execute the pinned .py.
|
|
379
|
+
sys.pycache_prefix = str(cache)
|
|
380
|
+
sys.dont_write_bytecode = True
|
|
381
|
+
os.environ["GNE_CONFIGS"] = str(Path(root) / "configs")
|
|
382
|
+
sys.path.insert(0, str(root))
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def verify_gguf(root, model, identity):
|
|
386
|
+
require(model.get("schema") == "omnius.nol.model.v1" and model.get("format") == "gguf", "Only a frozen GGUF model is supported", "UNSUPPORTED")
|
|
387
|
+
verify_identity(identity["modelJson"], {key: value for key, value in model.items() if key not in ("id", "modelDigest")}, model["modelDigest"])
|
|
388
|
+
verify_identity(identity["tensorSitesJson"], model["tensorSites"], model["architectureMapDigest"])
|
|
389
|
+
require(len(model["files"]) == 1 and model["files"][0]["role"] == "weights", "Split GGUF and external model files require a separate lowering", "UNSUPPORTED")
|
|
390
|
+
part = model["files"][0]
|
|
391
|
+
fields(part, ("path", "role", "artifact"))
|
|
392
|
+
path = safe_path(root, part["path"])
|
|
393
|
+
require(hash_file(path) == {"sha256": part["artifact"]["sha256"], "sizeBytes": part["artifact"]["sizeBytes"]}, "Complete GGUF file digest mismatch", "IDENTITY")
|
|
394
|
+
metadata = gguf_metadata(path)
|
|
395
|
+
require(metadata["metadata"].get("split.count", 1) == 1, "Split GGUF shards require a complete separately verified loader", "UNSUPPORTED")
|
|
396
|
+
verify_identity(identity["tokenizerJson"], metadata["tokenizer"], model["tokenizerDigest"])
|
|
397
|
+
aliases = {"pad": "padding", "unk": "unknown", "sep": "seperator"}
|
|
398
|
+
vocabulary = metadata["tokenizer"].get("tokenizer.ggml.tokens", [])
|
|
399
|
+
for name, token_id in model["specialTokens"].items():
|
|
400
|
+
actual = metadata["tokenizer"].get("tokenizer.ggml." + aliases.get(name, name) + "_token_id")
|
|
401
|
+
if actual is None and name in vocabulary and vocabulary.count(name) == 1: actual = vocabulary.index(name)
|
|
402
|
+
require(actual == token_id, "Special-token mapping differs from complete GGUF metadata", "IDENTITY")
|
|
403
|
+
require(digest_bytes(metadata["template"].encode()) == model["chatTemplateDigest"], "GGUF metadata template differs from frozen effective template", "IDENTITY")
|
|
404
|
+
arch = metadata["architecture"]
|
|
405
|
+
require(metadata["metadata"].get(arch + ".block_count") == model["architecture"]["layers"] and metadata["metadata"].get(arch + ".embedding_length") == model["architecture"]["hiddenSize"], "GGUF dimensions differ from frozen architecture", "IDENTITY")
|
|
406
|
+
return path, metadata
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
class Runtime:
|
|
410
|
+
def __init__(self):
|
|
411
|
+
self.session = None
|
|
412
|
+
self.loaded = self.confirmed = False
|
|
413
|
+
self.manifest = self.binding = self.limits = self.sites = None
|
|
414
|
+
self.gpu_uuid = self.artifact_root = None
|
|
415
|
+
self.temp = None
|
|
416
|
+
self.reset_epoch = 0
|
|
417
|
+
self.last_reset = None
|
|
418
|
+
self.created_loras = []
|
|
419
|
+
self.profile_sequence = 0
|
|
420
|
+
self.profile_output_bytes = 0
|
|
421
|
+
self.validated_cells = {}
|
|
422
|
+
self.runtime_build = None
|
|
423
|
+
|
|
424
|
+
def inspect(self, payload):
|
|
425
|
+
fields(payload, ("gneRoot",), ("checkpointPath", "dependencyLockPath", "hashRuntime", "maxRuntimeBytes", "tensorSites", "columns", "columnLimits", "expectedFile"))
|
|
426
|
+
metadata = gguf_metadata(payload["checkpointPath"]) if "checkpointPath" in payload else None
|
|
427
|
+
result = {"runtime": gne_build(payload["gneRoot"], payload.get("dependencyLockPath"), payload.get("hashRuntime") is True, metadata,
|
|
428
|
+
integer(payload.get("maxRuntimeBytes", 34359738368), 1))}
|
|
429
|
+
if metadata is not None:
|
|
430
|
+
tokenizer_json = canonical_gguf(metadata["tokenizer"])
|
|
431
|
+
result["checkpoint"] = {"file": hash_file(payload["checkpointPath"]), "architecture": metadata["architecture"],
|
|
432
|
+
"metadata": {key: value for key, value in metadata["metadata"].items() if not key.startswith("tokenizer.")},
|
|
433
|
+
"tokenizerJson": tokenizer_json, "tokenizerDigest": digest_bytes(tokenizer_json.encode()),
|
|
434
|
+
"chatTemplate": metadata["template"], "denseMlpLayers": metadata["denseMlpLayers"],
|
|
435
|
+
"unsupportedLayers": metadata["unsupportedLayers"], "reservedLayers": metadata["reservedLayers"],
|
|
436
|
+
"unsupportedSiteIds": [site["id"] for site in payload.get("tensorSites", []) if site.get("kind") == "mlp_intermediate" and site.get("layer") not in metadata["denseMlpLayers"]], **renderer_facts(metadata)}
|
|
437
|
+
if any(key in payload for key in ("columns", "columnLimits", "expectedFile")):
|
|
438
|
+
require(not self.loaded and metadata is not None and all(key in payload for key in ("columns", "columnLimits", "expectedFile")),
|
|
439
|
+
"Explicit CPU columns require an unloaded worker, full checkpoint and all admission bounds")
|
|
440
|
+
result["columnNorms"] = gguf_column_norms(payload["checkpointPath"], payload["columns"], payload["columnLimits"], payload["expectedFile"], metadata)
|
|
441
|
+
return result
|
|
442
|
+
|
|
443
|
+
def load(self, payload):
|
|
444
|
+
fields(payload, ("checkpointRoot", "artifactRoot", "workRoot", "gneRoot", "model", "binding", "gpuUuid", "identity", "dependencyLockPath", "limits"))
|
|
445
|
+
require(not self.loaded, "Worker already loaded")
|
|
446
|
+
self.validated_cells.clear()
|
|
447
|
+
uuid = payload["gpuUuid"]
|
|
448
|
+
require(type(uuid) is str and UUID.fullmatch(uuid) and os.environ.get("CUDA_VISIBLE_DEVICES") == uuid, "Explicit exact single-GPU CUDA scope is required", "PLACEMENT")
|
|
449
|
+
fields(payload["limits"], ("maxInputTokens", "maxOutputTokens", "maxTensorBytes", "maxWorkingBytes", "maxMultiplyAdds"))
|
|
450
|
+
limits = {key: integer(value, 1) for key, value in payload["limits"].items()}
|
|
451
|
+
identity = payload["identity"]
|
|
452
|
+
fields(identity, ("modelJson", "tensorSitesJson", "tokenizerJson", "runtimeBuildJson"))
|
|
453
|
+
root, gne_root = Path(payload["checkpointRoot"]).resolve(strict=True), Path(payload["gneRoot"]).resolve(strict=True)
|
|
454
|
+
path, metadata = verify_gguf(root, payload["model"], identity)
|
|
455
|
+
build = gne_build(gne_root, payload["dependencyLockPath"], True, metadata)
|
|
456
|
+
verify_identity(identity["runtimeBuildJson"], build, payload["binding"]["runtimeBuildDigest"])
|
|
457
|
+
binding, manifest = payload["binding"], payload["model"]
|
|
458
|
+
require(binding["schema"] == "omnius.nol.runtime.v1" and binding["backend"] == "gne" and
|
|
459
|
+
all(binding[key] == manifest[key] for key in ("modelDigest", "architectureMapDigest", "tokenizerDigest", "chatTemplateDigest")) and
|
|
460
|
+
build["dependencyLockDigest"] == binding["dependencyLockDigest"], "GNE runtime/model binding mismatch", "IDENTITY")
|
|
461
|
+
require(limits["maxInputTokens"] + limits["maxOutputTokens"] <= binding["contextLimit"] <= manifest["contextLength"], "Context budget mismatch", "CAPACITY")
|
|
462
|
+
work_root = Path(payload["workRoot"]).resolve(strict=True)
|
|
463
|
+
artifact_root = Path(payload["artifactRoot"]).resolve(strict=True)
|
|
464
|
+
require(work_root.is_dir() and not work_root.is_relative_to(root) and not work_root.is_relative_to(artifact_root), "GNE working files require a separate host-owned scratch directory")
|
|
465
|
+
# Only this explicit, fully verified load boundary imports GNE/native code.
|
|
466
|
+
self.temp = tempfile.TemporaryDirectory(prefix="omnius-gne-", dir=work_root)
|
|
467
|
+
isolate_gne_imports(gne_root, self.temp.name)
|
|
468
|
+
from gne.api import Session
|
|
469
|
+
from gne.steer import Recipe, Unit, recipe_vectors
|
|
470
|
+
from gne.engine import Sampling
|
|
471
|
+
from gne.gain import export_gain_lora
|
|
472
|
+
import resource
|
|
473
|
+
import gne.api
|
|
474
|
+
require(Path(gne.api.__file__).resolve() == gne_root / "gne" / "api.py", "Imported GNE escaped the pinned source", "IDENTITY")
|
|
475
|
+
# Native adapter files are transient scratch, never published artifacts.
|
|
476
|
+
# Bound even a partially failed upstream writer before its first byte.
|
|
477
|
+
soft, hard = resource.getrlimit(resource.RLIMIT_FSIZE)
|
|
478
|
+
maximum = limits["maxTensorBytes"]
|
|
479
|
+
if soft != resource.RLIM_INFINITY: maximum = min(maximum, soft)
|
|
480
|
+
if hard != resource.RLIM_INFINITY: maximum = min(maximum, hard)
|
|
481
|
+
resource.setrlimit(resource.RLIMIT_FSIZE, (maximum, hard))
|
|
482
|
+
self.Recipe, self.Unit, self.recipe_vectors, self.Sampling, self.export_gain_lora = Recipe, Unit, recipe_vectors, Sampling, export_gain_lora
|
|
483
|
+
try:
|
|
484
|
+
self.session = Session(path, root=self.temp.name, n_gpu_layers=-1, n_ctx=binding["contextLimit"], n_seq_max=1, seed=0, verbose=False)
|
|
485
|
+
engine = self.session.engine
|
|
486
|
+
require(digest_bytes(engine.chat_template.encode()) == manifest["chatTemplateDigest"] and engine.n_embd == manifest["architecture"]["hiddenSize"], "Effective GNE renderer/architecture differs from frozen identity", "IDENTITY")
|
|
487
|
+
# Create the complete fixed-size generation context without decoding
|
|
488
|
+
# any token; host placement must be confirmed before native prefill.
|
|
489
|
+
engine.steer_ctx()
|
|
490
|
+
self.manifest, self.binding, self.limits, self.runtime_build = manifest, binding, limits, build
|
|
491
|
+
self.gpu_uuid, self.artifact_root = uuid, artifact_root
|
|
492
|
+
self.sites = {}
|
|
493
|
+
for site in manifest["tensorSites"]:
|
|
494
|
+
if site["kind"] == "mlp_intermediate":
|
|
495
|
+
require(site["id"] not in self.sites and site["layer"] in metadata["denseMlpLayers"] and 0 <= site["layer"] < engine.n_layer and site["width"] == self.session.meta.n_ff_at(site["layer"]), "Native MLP site differs from frozen architecture or addresses an unsupported/MTP layer", "IDENTITY")
|
|
496
|
+
self.sites[site["id"]] = site
|
|
497
|
+
self.loaded = True
|
|
498
|
+
supported = sorted(RUNTIME_OPS) if self.session.meta.arch in ("llama", "qwen2", "qwen3", "qwen3next", "qwen35") else []
|
|
499
|
+
if self.session.meta.has_post_ffn_norm and "NEURON_ADD" in supported: supported.remove("NEURON_ADD")
|
|
500
|
+
return {"loaded": True, "zeroTokensGenerated": True, "pid": os.getpid(), "binding": binding,
|
|
501
|
+
"runtime": build, "renderer": renderer_facts(metadata), "placement": placement(uuid), "confirmed": False,
|
|
502
|
+
"implementation": WORKER_VERSION, "supportedRuntimeOperations": supported, "supportedParameterOperations": [], "siteIds": sorted(self.sites),
|
|
503
|
+
"operationRestrictions": {"tokenScope": "all_only", "units": ["raw", "residual_norm_with_frozen_statistics"], "overlappingOperations": "unsupported", "neuronAddLayer0": "unsupported", "gain": "dense_separate_swiglu_up_lora"},
|
|
504
|
+
"tokenScopeBasis": "edited_computation_positions", "firstGeneratedTokenUsesPromptComputation": True,
|
|
505
|
+
"usesCache": True, "cacheScope": "within_trial_only",
|
|
506
|
+
"native": {"architecture": self.session.meta.arch, "layers": engine.n_layer, "hiddenSize": engine.n_embd, "llamaCppVersion": engine.llama_cpp_version()}}
|
|
507
|
+
except BaseException:
|
|
508
|
+
self.close()
|
|
509
|
+
raise
|
|
510
|
+
|
|
511
|
+
def confirm(self, payload):
|
|
512
|
+
fields(payload, ("pid", "gpuUuid", "startIdentity"))
|
|
513
|
+
require(self.loaded and same_json(payload, placement(self.gpu_uuid)), "Host placement confirmation differs from actual CUDA worker", "PLACEMENT")
|
|
514
|
+
self.confirmed = True
|
|
515
|
+
return {"confirmed": True, "binding": self.binding, "placement": payload}
|
|
516
|
+
|
|
517
|
+
def ready(self):
|
|
518
|
+
require(self.loaded and self.confirmed, "Model requires actual host-confirmed CUDA placement", "PLACEMENT")
|
|
519
|
+
|
|
520
|
+
def tokenize(self, payload):
|
|
521
|
+
self.ready()
|
|
522
|
+
fields(payload, ("messages",))
|
|
523
|
+
messages = payload["messages"]
|
|
524
|
+
require(type(messages) is list and 0 < len(messages) <= 1000, "Invalid message inventory")
|
|
525
|
+
for message in messages:
|
|
526
|
+
fields(message, ("role", "content"))
|
|
527
|
+
require(message["role"] in ("system", "user", "assistant") and type(message["content"]) is str, "Only plain text chat is supported", "UNSUPPORTED")
|
|
528
|
+
engine = self.session.engine
|
|
529
|
+
text = engine.render_chat(messages, enable_thinking=False, add_generation_prompt=True)
|
|
530
|
+
ids = engine.tokenize_prompt(text)
|
|
531
|
+
require(0 < len(ids) <= self.limits["maxInputTokens"], "Native prompt budget exceeded", "CAPACITY")
|
|
532
|
+
return {"tokenIds": ids, "promptTokens": len(ids), "renderedPrompt": text, "chatTemplateDigest": digest_bytes(engine.chat_template.encode())}
|
|
533
|
+
|
|
534
|
+
def reset(self):
|
|
535
|
+
if self.session is not None and self.session._engine is not None:
|
|
536
|
+
engine = self.session.engine
|
|
537
|
+
for ctx in (engine._steer, engine._probe, engine._attn_probe):
|
|
538
|
+
if ctx is not None:
|
|
539
|
+
engine.set_cvec(ctx, None)
|
|
540
|
+
engine.set_lora(ctx, None)
|
|
541
|
+
engine.clear_memory(ctx)
|
|
542
|
+
for path in self.created_loras:
|
|
543
|
+
engine.drop_lora(path)
|
|
544
|
+
Path(path).unlink(missing_ok=True)
|
|
545
|
+
self.created_loras = []
|
|
546
|
+
self.session.weights._cache.clear()
|
|
547
|
+
self.reset_epoch += 1
|
|
548
|
+
self.last_reset = {"epoch": self.reset_epoch, "controlVectors": 0, "activeAdapters": [], "kvCleared": True, "clean": True, "modelDigest": self.manifest["modelDigest"] if self.manifest else None}
|
|
549
|
+
return self.last_reset
|
|
550
|
+
|
|
551
|
+
def calibration(self, recipe, operation, layer):
|
|
552
|
+
calibration = next((value for value in recipe["calibrations"] if value["id"] == operation.get("calibrationId")), None)
|
|
553
|
+
require(calibration is not None and calibration["units"] == "residual_norm" and calibration["modelDigest"] == self.manifest["modelDigest"] and calibration["architectureMapDigest"] == self.manifest["architectureMapDigest"], "Explicit residual calibration must bind the exact model/site map", "IDENTITY")
|
|
554
|
+
artifact = calibration.get("statistics")
|
|
555
|
+
require(type(artifact) is dict and artifact.get("uri") == "omnius-artifact://sha256/" + str(artifact.get("sha256")) and SHA.fullmatch(artifact.get("sha256", "")), "Measured residual statistics artifact required", "UNSUPPORTED")
|
|
556
|
+
path = safe_path(self.artifact_root, artifact["sha256"][:2] + "/" + artifact["sha256"])
|
|
557
|
+
require(hash_file(path, self.limits["maxTensorBytes"]) == {"sha256": artifact["sha256"], "sizeBytes": artifact["sizeBytes"]}, "Residual statistics bytes differ from frozen calibration", "IDENTITY")
|
|
558
|
+
from gne.stats import ResidStats
|
|
559
|
+
stats = ResidStats.load(path)
|
|
560
|
+
corpus_digest, positions_digest = calibration.get("corpusDigest"), calibration.get("tokenPositionsDigest")
|
|
561
|
+
require(SHA.fullmatch(corpus_digest or "") and SHA.fullmatch(positions_digest or ""), "Full corpus and position identities are required", "IDENTITY")
|
|
562
|
+
for digest in (corpus_digest, positions_digest):
|
|
563
|
+
source = safe_path(self.artifact_root, digest[:2] + "/" + digest)
|
|
564
|
+
require(hash_file(source, self.limits["maxTensorBytes"])["sha256"] == digest, "Calibration source bytes differ from their full frozen identity", "IDENTITY")
|
|
565
|
+
corpus = safe_path(self.artifact_root, corpus_digest[:2] + "/" + corpus_digest)
|
|
566
|
+
# Upstream hashes decoded/universal-newline text, then truncates its
|
|
567
|
+
# corpus tag to 16 hex characters. Full CAS bytes remain authoritative.
|
|
568
|
+
text_digest = digest_bytes(corpus.read_text(encoding="utf-8").encode("utf-8"))
|
|
569
|
+
scale = next((item["scale"] for item in calibration["siteScales"] if item["siteId"] == operation["siteId"]), None)
|
|
570
|
+
require(stats.n_tokens > 0 and stats.corpus_sha in (corpus_digest, text_digest, text_digest[:16]) and scale is not None and number(scale) > 0 and stats.rho(layer) == scale, "Measured residual median/corpus differs from the explicit calibration", "IDENTITY")
|
|
571
|
+
return stats
|
|
572
|
+
|
|
573
|
+
def profile(self, payload):
|
|
574
|
+
require(type(payload) is dict, "Profile payload must be an object")
|
|
575
|
+
if payload.get("mode") == "neuron_add_conformance":
|
|
576
|
+
return self.conformance(payload)
|
|
577
|
+
if payload.get("mode") == "accept_neuron_add_conformance":
|
|
578
|
+
return self.accept_conformance(payload)
|
|
579
|
+
self.ready()
|
|
580
|
+
fields(payload, ("corpusArtifact", "layers", "chunkTokens", "maxTokens"), ("neurons",))
|
|
581
|
+
require(self.last_reset is not None and not self.created_loras, "Residual profile requires an explicit clean host reset", "RESET")
|
|
582
|
+
artifact = payload["corpusArtifact"]
|
|
583
|
+
fields(artifact, ("uri", "sha256", "sizeBytes", "mediaType"))
|
|
584
|
+
require(SHA.fullmatch(artifact["sha256"]) and artifact["uri"] == "omnius-artifact://sha256/" + artifact["sha256"] and artifact["mediaType"] in ("text/plain", "text/plain; charset=utf-8"), "Explicit UTF-8 corpus artifact required", "IDENTITY")
|
|
585
|
+
source = safe_path(self.artifact_root, artifact["sha256"][:2] + "/" + artifact["sha256"])
|
|
586
|
+
source_bound = min(self.limits["maxTensorBytes"], self.limits["maxWorkingBytes"] // 256)
|
|
587
|
+
require(hash_file(source, source_bound) == {"sha256": artifact["sha256"], "sizeBytes": artifact["sizeBytes"]}, "Corpus bytes differ from the full frozen identity", "IDENTITY")
|
|
588
|
+
layers = payload["layers"]
|
|
589
|
+
engine = self.session.engine
|
|
590
|
+
require(type(layers) is list and 0 < len(layers) <= engine.n_layer and len(set(layers)) == len(layers), "Explicit unique residual layers required")
|
|
591
|
+
for layer in layers: integer(layer, 1, engine.n_layer - 1)
|
|
592
|
+
require(all(any(site["layer"] == layer for site in self.sites.values()) for layer in layers), "Calibration layer is not an editable dense native site", "UNSUPPORTED")
|
|
593
|
+
neurons = payload.get("neurons", [])
|
|
594
|
+
require(type(neurons) is list and len(neurons) <= 64, "Column measurement inventory exceeds its bound", "CAPACITY")
|
|
595
|
+
coordinates = set()
|
|
596
|
+
matrix_bytes = 0
|
|
597
|
+
column_arithmetic = 0
|
|
598
|
+
for neuron in neurons:
|
|
599
|
+
fields(neuron, ("layer", "neuron"))
|
|
600
|
+
layer = integer(neuron["layer"], 1, engine.n_layer - 1)
|
|
601
|
+
require(layer in layers, "Column measurement layer must be included in the residual profile")
|
|
602
|
+
index = integer(neuron["neuron"], 0, self.session.meta.n_ff_at(layer) - 1)
|
|
603
|
+
require((layer, index) not in coordinates, "Duplicate column measurement coordinate")
|
|
604
|
+
coordinates.add((layer, index))
|
|
605
|
+
matrix_bytes = max(matrix_bytes, engine.n_embd * self.session.meta.n_ff_at(layer) * 4)
|
|
606
|
+
column_arithmetic += engine.n_embd * self.session.meta.n_ff_at(layer) * 4
|
|
607
|
+
chunk = integer(payload["chunkTokens"], 2, min(self.limits["maxInputTokens"], self.binding["contextLimit"]))
|
|
608
|
+
maximum = integer(payload["maxTokens"], chunk, self.limits["maxInputTokens"])
|
|
609
|
+
require(maximum % chunk == 0, "Profile maxTokens must be a multiple of chunkTokens to prevent upstream ceiling overshoot", "CAPACITY")
|
|
610
|
+
include_last = engine.n_layer - 1 in layers
|
|
611
|
+
capture_bytes = len(layers) * chunk * engine.n_embd * 4
|
|
612
|
+
working = capture_bytes * 4 + maximum * len(layers) * 16 + artifact["sizeBytes"] * 128
|
|
613
|
+
working += matrix_bytes * 4 + len(neurons) * engine.n_embd * 8
|
|
614
|
+
if include_last: working += chunk * engine.n_vocab * 4
|
|
615
|
+
require(capture_bytes <= self.limits["maxTensorBytes"] and working <= self.limits["maxWorkingBytes"] and maximum * len(layers) * engine.n_embd * 2 + column_arithmetic <= self.limits["maxMultiplyAdds"], "Residual profile exceeds frozen capture/working/arithmetic bounds", "CAPACITY")
|
|
616
|
+
from gne.stats import Corpus, corpus_chunks, residual_norms
|
|
617
|
+
text = source.read_text(encoding="utf-8")
|
|
618
|
+
corpus = Corpus(text, artifact["sha256"], str(source))
|
|
619
|
+
planned = corpus_chunks(engine, corpus, chunk_tokens=chunk, max_tokens=maximum)
|
|
620
|
+
require(type(planned) is list and planned and sum(len(tokens) for tokens in planned) <= maximum and all(2 <= len(tokens) <= chunk for tokens in planned), "Actual upstream chunks exceed the declared token bound", "CAPACITY")
|
|
621
|
+
before = self.last_reset
|
|
622
|
+
original_prefill, original_decode = engine.prefill, engine._decode
|
|
623
|
+
chunks, current = [], {"tokens": [], "positions": []}
|
|
624
|
+
def decode(ctx, items):
|
|
625
|
+
require(ctx is engine._probe and all(item[2] == 0 for item in items), "Profile decoded outside its owned single-sequence probe", "IDENTITY")
|
|
626
|
+
result = original_decode(ctx, items)
|
|
627
|
+
current["tokens"].extend(item[0] for item in items)
|
|
628
|
+
current["positions"].extend(item[1] for item in items)
|
|
629
|
+
return result
|
|
630
|
+
def prefill(ctx, sequences, **kwargs):
|
|
631
|
+
index = len(chunks)
|
|
632
|
+
require(index < len(planned) and len(sequences) == 1 and sequences[0] == planned[index], "Actual residual profile tokens differ from the bounded plan", "IDENTITY")
|
|
633
|
+
current["tokens"], current["positions"] = [], []
|
|
634
|
+
result = original_prefill(ctx, sequences, **kwargs)
|
|
635
|
+
require(current["tokens"] == planned[index] and current["positions"] == list(range(len(planned[index]))), "Native residual decode positions differ from the profile plan", "IDENTITY")
|
|
636
|
+
chunks.append({"chunkIndex": index, "tokenIds": list(current["tokens"]), "decodedPositions": list(current["positions"]), "measuredPositions": list(range(1, len(planned[index])))})
|
|
637
|
+
return result
|
|
638
|
+
def free_probe():
|
|
639
|
+
probe = engine._probe
|
|
640
|
+
if probe is not None:
|
|
641
|
+
engine.set_cvec(probe, None)
|
|
642
|
+
engine.set_lora(probe, None)
|
|
643
|
+
engine.clear_memory(probe)
|
|
644
|
+
probe.free()
|
|
645
|
+
engine._probe = None
|
|
646
|
+
engine._probe_logits_all = False
|
|
647
|
+
def save(name, data, media_type):
|
|
648
|
+
require(self.profile_output_bytes + len(data) <= self.limits["maxTensorBytes"], "Cumulative profile scratch output byte bound exceeded", "CAPACITY")
|
|
649
|
+
path = Path(self.temp.name) / name
|
|
650
|
+
# Failed/partial writes remain conservatively charged as scratch.
|
|
651
|
+
self.profile_output_bytes += len(data)
|
|
652
|
+
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
|
653
|
+
with os.fdopen(descriptor, "wb") as target: target.write(data)
|
|
654
|
+
return {"path": str(path), "sha256": digest_bytes(data), "sizeBytes": len(data), "mediaType": media_type}
|
|
655
|
+
try:
|
|
656
|
+
free_probe()
|
|
657
|
+
column_norms = []
|
|
658
|
+
try:
|
|
659
|
+
for neuron in neurons:
|
|
660
|
+
weights = self.session.weights
|
|
661
|
+
weights._cache.clear()
|
|
662
|
+
column = weights.down_column(neuron["layer"], neuron["neuron"])
|
|
663
|
+
require(len(column) == engine.n_embd and all(math.isfinite(float(value)) for value in column), "Native down-column shape/values differ from the model binding", "IDENTITY")
|
|
664
|
+
norm = math.sqrt(math.fsum(float(value) ** 2 for value in column))
|
|
665
|
+
scale = number((getattr(self.session.meta, "ffn_down_scale", None) or {}).get(neuron["layer"], 1.0))
|
|
666
|
+
require(norm > 0 and scale != 0, "Zero down-column or scale cannot define a residual dose", "UNSUPPORTED")
|
|
667
|
+
column_norms.append({**neuron, "columnL2": norm, "ffnDownScale": scale, "effectiveColumnL2": abs(scale) * norm})
|
|
668
|
+
finally:
|
|
669
|
+
self.session.weights._cache.clear()
|
|
670
|
+
engine.prefill, engine._decode = prefill, decode
|
|
671
|
+
stats = residual_norms(engine, corpus, layers=list(layers), chunk_tokens=chunk, include_last_layer=include_last, max_tokens=maximum)
|
|
672
|
+
require(len(chunks) == len(planned) and stats.n_tokens == sum(len(item["measuredPositions"]) for item in chunks) and list(int(layer) for layer in stats.layers) == list(layers), "Native profile statistics/positions inventory mismatch", "IDENTITY")
|
|
673
|
+
require(stats.corpus_sha == artifact["sha256"] and stats.exclude_pos0 is True, "Residual statistics lost full corpus/position identity", "IDENTITY")
|
|
674
|
+
summaries = stats.to_dict()
|
|
675
|
+
require(all(math.isfinite(float(value)) for key in ("p10", "p50", "p90", "mean") for value in summaries[key]) and all(stats.rho(layer) > 0 for layer in layers), "Residual calibration has nonfinite or zero medians")
|
|
676
|
+
for column in column_norms:
|
|
677
|
+
column["rho"] = stats.rho(column["layer"])
|
|
678
|
+
column["rawUnitsPerDose"] = column["rho"] / (column["ffnDownScale"] * column["columnL2"])
|
|
679
|
+
number(column["effectiveColumnL2"]); number(column["rawUnitsPerDose"])
|
|
680
|
+
definition = {"schema": "omnius.nol.residual-definition.v1", "implementation": WORKER_VERSION, "gneRevision": GNE_REVISION,
|
|
681
|
+
"algorithm": "gne.stats.residual_norms", "measure": "median_l2_l_out", "positionBasis": "chunk_local_excluding_zero",
|
|
682
|
+
"layerNumbering": "gguf_blk_zero_based", "sourceText": "utf8_universal_newlines", "sampledTokens": 0,
|
|
683
|
+
"columnNorm": "float64_l2_dequantized_ffn_down_column", "rawUnitsPerDose": "rho/(ffn_down.scale*column_l2)"}
|
|
684
|
+
definition_digest = digest_bytes(canonical_simple(definition).encode())
|
|
685
|
+
positions = {"schema": "omnius.nol.residual-positions.v1", "modelDigest": self.manifest["modelDigest"], "architectureMapDigest": self.manifest["architectureMapDigest"],
|
|
686
|
+
"corpusDigest": artifact["sha256"], "corpusTextDigest": digest_bytes(text.encode()), "tokenizerDigest": self.manifest["tokenizerDigest"],
|
|
687
|
+
"definitionDigest": definition_digest, "layers": layers, "chunkTokens": chunk, "maxTokens": maximum, "chunks": chunks}
|
|
688
|
+
positions_bytes = canonical_simple(positions).encode()
|
|
689
|
+
require(65536 + len(layers) * 128 + len(positions_bytes) + self.profile_output_bytes <= self.limits["maxTensorBytes"], "Profile serialization exceeds its reserved scratch byte bound", "CAPACITY")
|
|
690
|
+
buffer = io.BytesIO()
|
|
691
|
+
stats.save(buffer)
|
|
692
|
+
statistics_bytes = buffer.getvalue()
|
|
693
|
+
require(len(statistics_bytes) + len(positions_bytes) + self.profile_output_bytes <= self.limits["maxTensorBytes"], "Profile artifacts exceed the cumulative byte bound", "CAPACITY")
|
|
694
|
+
self.profile_sequence += 1
|
|
695
|
+
statistics_file = save(f"residual-{self.profile_sequence}.npz", statistics_bytes, "application/x-npz")
|
|
696
|
+
positions_file = save(f"residual-{self.profile_sequence}.positions.json", positions_bytes, "application/json")
|
|
697
|
+
engine.prefill, engine._decode = original_prefill, original_decode
|
|
698
|
+
free_probe()
|
|
699
|
+
after = self.reset()
|
|
700
|
+
return {"sampledTokens": 0, "corpusDigest": artifact["sha256"], "definition": definition, "definitionDigest": definition_digest,
|
|
701
|
+
"layers": layers, "chunkTokens": chunk, "inputTokens": sum(len(tokens) for tokens in planned), "statistics": summaries,
|
|
702
|
+
"statisticsFile": statistics_file, "positionsFile": positions_file,
|
|
703
|
+
"columns": column_norms,
|
|
704
|
+
"siteScales": [{"siteId": site["id"], "scale": stats.rho(site["layer"])} for site in self.sites.values() if site["layer"] in layers],
|
|
705
|
+
"native": {"binding": self.binding, "implementation": WORKER_VERSION, "resetBefore": before, "resetAfter": after,
|
|
706
|
+
"probeFreed": True, "usesCache": True, "cacheScope": "profile_only_cleared", "sourceArtifact": artifact}}
|
|
707
|
+
except BaseException:
|
|
708
|
+
engine.prefill, engine._decode = original_prefill, original_decode
|
|
709
|
+
try:
|
|
710
|
+
free_probe()
|
|
711
|
+
self.reset()
|
|
712
|
+
except BaseException as error: raise Rejected("RESET", "Residual profile could not release its probe state", True) from error
|
|
713
|
+
raise
|
|
714
|
+
|
|
715
|
+
def cell_key(self, operation):
|
|
716
|
+
return canonical_gguf({key: operation.get(key) for key in ("siteId", "neuron", "amount", "units", "tokenScope", "calibrationId")})
|
|
717
|
+
|
|
718
|
+
def conformance(self, payload):
|
|
719
|
+
"""Explicit bounded native measurements; no sampled/generated token."""
|
|
720
|
+
self.ready()
|
|
721
|
+
fields(payload, ("mode", "messages", "operations", "maxTokens", "absoluteTolerance", "relativeTolerance"))
|
|
722
|
+
require(self.last_reset is not None and not self.created_loras, "Conformance requires an explicit clean reset", "RESET")
|
|
723
|
+
operations = payload["operations"]
|
|
724
|
+
require(type(operations) is list and 0 < len(operations) <= 8, "Conformance cell inventory exceeds its bound", "CAPACITY")
|
|
725
|
+
absolute, relative = number(payload["absoluteTolerance"]), number(payload["relativeTolerance"])
|
|
726
|
+
require(0 < absolute <= 0.01 and 0 < relative <= 0.01, "Explicit bounded FP tolerances required")
|
|
727
|
+
engine = self.session.engine
|
|
728
|
+
tokens = self.tokenize({"messages": payload["messages"]})["tokenIds"]
|
|
729
|
+
maximum = integer(payload["maxTokens"], 1, self.limits["maxInputTokens"] * 24)
|
|
730
|
+
require(len(tokens) * 3 * len(operations) <= maximum, "Conformance three-prefill token budget exceeded", "CAPACITY")
|
|
731
|
+
keys, matrix_bytes = set(), 0
|
|
732
|
+
for operation in operations:
|
|
733
|
+
fields(operation, ("id", "operation", "siteId", "tokenScope", "neuron", "amount", "units"))
|
|
734
|
+
require(operation["operation"] == "NEURON_ADD" and operation["units"] == "raw" and operation["tokenScope"] == {"kind": "all"},
|
|
735
|
+
"Conformance supports raw all-token neuron-add cells only", "UNSUPPORTED")
|
|
736
|
+
require(number(operation["amount"]) != 0 and self.cell_key(operation) not in keys, "Conformance requires distinct nonzero cells")
|
|
737
|
+
keys.add(self.cell_key(operation))
|
|
738
|
+
site = self.sites.get(operation["siteId"])
|
|
739
|
+
require(site is not None and 0 < site["layer"] < engine.n_layer and not self.session.meta.has_post_ffn_norm,
|
|
740
|
+
"Conformance cannot validate this layer or post-FFN normalized architecture", "UNSUPPORTED")
|
|
741
|
+
integer(operation["neuron"], 0, site["width"] - 1)
|
|
742
|
+
matrix_bytes = max(matrix_bytes, engine.n_embd * site["width"] * 4)
|
|
743
|
+
for key in keys: self.validated_cells.pop(key, None)
|
|
744
|
+
capture_bytes = len(operations) * (6 * len(tokens) + 1) * engine.n_embd * 4
|
|
745
|
+
require(capture_bytes + self.profile_output_bytes + 65536 <= self.limits["maxTensorBytes"] and
|
|
746
|
+
matrix_bytes * 4 + capture_bytes * 16 <= self.limits["maxWorkingBytes"] and
|
|
747
|
+
maximum * engine.n_embd * 4 <= self.limits["maxMultiplyAdds"], "Conformance capture/dequantization/working budget exceeded", "CAPACITY")
|
|
748
|
+
from gne.capture import Capture
|
|
749
|
+
import numpy as np
|
|
750
|
+
before, original_decode = self.last_reset, engine._decode
|
|
751
|
+
captures, cells, decoded = {}, [], []
|
|
752
|
+
def decode(ctx, items):
|
|
753
|
+
require(ctx is engine._probe and all(item[2] == 0 for item in items), "Conformance escaped its owned single-sequence probe", "IDENTITY")
|
|
754
|
+
result = original_decode(ctx, items)
|
|
755
|
+
decoded.extend((item[0], item[1]) for item in items)
|
|
756
|
+
return result
|
|
757
|
+
def free_probe():
|
|
758
|
+
if engine._probe is not None:
|
|
759
|
+
engine.set_cvec(engine._probe, None); engine.set_lora(engine._probe, None); engine.clear_memory(engine._probe)
|
|
760
|
+
engine._probe.free(); engine._probe = None
|
|
761
|
+
try:
|
|
762
|
+
free_probe()
|
|
763
|
+
engine._decode = decode
|
|
764
|
+
for index, operation in enumerate(operations):
|
|
765
|
+
site, layer = self.sites[operation["siteId"]], self.sites[operation["siteId"]]["layer"]
|
|
766
|
+
names = (f"l_out-{layer - 1}", f"l_out-{layer}")
|
|
767
|
+
capture = Capture(lambda name: name in names)
|
|
768
|
+
ctx = engine.probe_ctx(capture, logits_all=layer == engine.n_layer - 1, need=len(tokens))
|
|
769
|
+
recipe = {"schema": "omnius.nol.recipe.v1", "modelDigest": self.manifest["modelDigest"],
|
|
770
|
+
"architectureMapDigest": self.manifest["architectureMapDigest"], "operations": [operation], "calibrations": []}
|
|
771
|
+
vectors, lora, actual = self.install(recipe, validating=True)
|
|
772
|
+
require(lora is None and set(vectors) == {layer}, "Conformance installed an unexpected adapter/layer", "IDENTITY")
|
|
773
|
+
vector = [number(float(value)) for value in vectors[layer]]
|
|
774
|
+
norm = math.sqrt(math.fsum(value * value for value in vector))
|
|
775
|
+
require(len(vector) == engine.n_embd and norm > 0, "Conformance lowering has no finite nonzero vector", "IDENTITY")
|
|
776
|
+
observed = {}
|
|
777
|
+
for phase, applied in (("baseline", None), ("steered", vectors), ("restored", None)):
|
|
778
|
+
decoded.clear(); capture.reset()
|
|
779
|
+
engine.set_lora(ctx, None); engine.set_cvec(ctx, applied); engine.clear_memory(ctx)
|
|
780
|
+
engine.prefill(ctx, [tokens], logits_all=layer == engine.n_layer - 1)
|
|
781
|
+
require(decoded == list(zip(tokens, range(len(tokens)))), "Actual conformance tokens/positions differ from its plan", "IDENTITY")
|
|
782
|
+
values = capture.take()
|
|
783
|
+
require(set(values) == set(names) and not capture.skipped, "Native residual capture is missing or skipped", "UNSUPPORTED")
|
|
784
|
+
observed[phase] = {}
|
|
785
|
+
for name in names:
|
|
786
|
+
array = values[name]
|
|
787
|
+
require(tuple(array.shape) == (len(tokens), engine.n_embd) and str(array.dtype) == "float32", "Native residual shape/dtype differs from admission", "IDENTITY")
|
|
788
|
+
rows = array.tolist()
|
|
789
|
+
require(all(math.isfinite(value) for row in rows for value in row), "Nonfinite native residual observation")
|
|
790
|
+
observed[phase][name] = rows
|
|
791
|
+
captures[f"cell_{index}_{phase}_{'prior' if name == names[0] else 'target'}"] = array
|
|
792
|
+
base, steered, restored = observed["baseline"], observed["steered"], observed["restored"]
|
|
793
|
+
prior_error = max(abs(a - b) for left, right in zip(base[names[0]], steered[names[0]]) for a, b in zip(left, right))
|
|
794
|
+
restoration = max(abs(a - b) for name in names for left, right in zip(base[name], restored[name]) for a, b in zip(left, right))
|
|
795
|
+
errors = [[actual_value - original - expected for actual_value, original, expected in zip(left, right, vector)]
|
|
796
|
+
for left, right in zip(steered[names[1]], base[names[1]])]
|
|
797
|
+
maximum_error = max(abs(value) for row in errors for value in row)
|
|
798
|
+
relative_error = max(math.sqrt(math.fsum(value * value for value in row)) / norm for row in errors)
|
|
799
|
+
coordinate_pass = all(abs(value) <= absolute + relative * abs(expected) for row in errors for value, expected in zip(row, vector))
|
|
800
|
+
passed = prior_error <= absolute and restoration <= absolute and coordinate_pass
|
|
801
|
+
vector_array = np.asarray(vector, dtype=np.float32)
|
|
802
|
+
captures[f"cell_{index}_vector"] = vector_array
|
|
803
|
+
cells.append({"operation": operation, "layer": layer, "tokenIds": list(tokens), "decodedPositions": list(range(len(tokens))),
|
|
804
|
+
"priorTensor": names[0], "targetTensor": names[1], "vectorNorm": norm,
|
|
805
|
+
"vectorSha256": digest_bytes(vector_array.tobytes()), "priorMaxAbsError": prior_error, "restorationMaxAbsError": restoration,
|
|
806
|
+
"deltaMaxAbsError": maximum_error, "deltaMaxRelativeL2Error": relative_error, "coordinateTolerancePassed": coordinate_pass,
|
|
807
|
+
"validationPassed": passed})
|
|
808
|
+
free_probe()
|
|
809
|
+
output = io.BytesIO(); np.savez(output, **captures); content = output.getvalue()
|
|
810
|
+
require(len(content) + self.profile_output_bytes <= self.limits["maxTensorBytes"], "Conformance proof exceeds its cumulative scratch reservation", "CAPACITY")
|
|
811
|
+
self.profile_sequence += 1
|
|
812
|
+
target = Path(self.temp.name) / f"conformance-{self.profile_sequence}.npz"
|
|
813
|
+
with target.open("xb") as stream: stream.write(content)
|
|
814
|
+
self.profile_output_bytes += len(content)
|
|
815
|
+
engine._decode = original_decode
|
|
816
|
+
after = self.reset()
|
|
817
|
+
report = {"schema": "omnius.nol.gne-add-conformance.v1", "binding": self.binding, "workerSha256": hash_file(Path(__file__).resolve())["sha256"],
|
|
818
|
+
"gneRevision": GNE_REVISION, "implementation": WORKER_VERSION, "procedure": "baseline_steered_restored_prior_and_target_residual_f32",
|
|
819
|
+
"positionBasis": "edited_computation_positions", "tokenScope": "all", "sampledTokens": 0, "inputTokens": len(tokens) * 3 * len(operations),
|
|
820
|
+
"absoluteTolerance": absolute, "relativeTolerance": relative, "cells": cells, "validationPassed": all(cell["validationPassed"] for cell in cells),
|
|
821
|
+
"capture": {"sha256": digest_bytes(content), "sizeBytes": len(content), "mediaType": "application/x-npz"},
|
|
822
|
+
"limitations": ["bounded_exact_cells_and_token_positions_only", "floating_point_validated_equivalent_not_exact", "no_efficacy_claim"]}
|
|
823
|
+
validation_id = digest_bytes(canonical_gguf(report).encode())
|
|
824
|
+
if report["validationPassed"]:
|
|
825
|
+
for operation in operations: self.validated_cells[self.cell_key(operation)] = validation_id
|
|
826
|
+
return {**report, "validationId": validation_id, "captureFile": {"path": str(target), **report["capture"]},
|
|
827
|
+
"native": {"binding": self.binding, "resetBefore": before, "resetAfter": after, "probeFreed": True, "cacheScope": "conformance_only_cleared"}}
|
|
828
|
+
except BaseException:
|
|
829
|
+
engine._decode = original_decode
|
|
830
|
+
try: free_probe(); self.reset()
|
|
831
|
+
except BaseException as error: raise Rejected("RESET", "Conformance probe state could not be released", True) from error
|
|
832
|
+
raise
|
|
833
|
+
|
|
834
|
+
def accept_conformance(self, payload):
|
|
835
|
+
"""Zero-token import over the private host channel; the host must first
|
|
836
|
+
verify its immutable issued journal record, not arbitrary caller JSON."""
|
|
837
|
+
self.ready()
|
|
838
|
+
fields(payload, ("mode", "evidenceArtifact"))
|
|
839
|
+
reference = payload["evidenceArtifact"]
|
|
840
|
+
fields(reference, ("uri", "sha256", "sizeBytes", "mediaType"))
|
|
841
|
+
require(SHA.fullmatch(reference["sha256"]) and reference["uri"] == "omnius-artifact://sha256/" + reference["sha256"] and reference["mediaType"] == "application/json", "Frozen conformance evidence artifact required", "IDENTITY")
|
|
842
|
+
path = safe_path(self.artifact_root, reference["sha256"][:2] + "/" + reference["sha256"])
|
|
843
|
+
require(hash_file(path, min(self.limits["maxTensorBytes"], 1048576)) == {"sha256": reference["sha256"], "sizeBytes": reference["sizeBytes"]}, "Conformance evidence bytes changed", "IDENTITY")
|
|
844
|
+
evidence = parse_json(path.read_text(encoding="utf-8"))
|
|
845
|
+
require(evidence.get("schema") == "omnius.nol.gne-conformance-evidence.v1", "Unsupported conformance evidence document")
|
|
846
|
+
report, capture = evidence.get("nativeReport"), evidence.get("captureArtifact")
|
|
847
|
+
require(type(report) is dict and type(capture) is dict and report.get("validationPassed") is True and same_json(report.get("binding"), self.binding) and
|
|
848
|
+
report.get("workerSha256") == hash_file(Path(__file__).resolve())["sha256"] and report.get("gneRevision") == GNE_REVISION and
|
|
849
|
+
report.get("procedure") == "baseline_steered_restored_prior_and_target_residual_f32" and report.get("tokenScope") == "all" and report.get("sampledTokens") == 0,
|
|
850
|
+
"Conformance proof is not validated for the exact native runtime/model", "IDENTITY")
|
|
851
|
+
body = {key: value for key, value in report.items() if key not in ("validationId", "captureFile", "native")}
|
|
852
|
+
require(report.get("validationId") == digest_bytes(canonical_gguf(body).encode()), "Conformance report identity changed", "IDENTITY")
|
|
853
|
+
require(capture.get("sha256") == report["capture"]["sha256"] and capture.get("sizeBytes") == report["capture"]["sizeBytes"] and capture.get("uri") == "omnius-artifact://sha256/" + capture["sha256"], "Capture artifact differs from observed proof", "IDENTITY")
|
|
854
|
+
source = safe_path(self.artifact_root, capture["sha256"][:2] + "/" + capture["sha256"])
|
|
855
|
+
require(hash_file(source, self.limits["maxTensorBytes"]) == {"sha256": capture["sha256"], "sizeBytes": capture["sizeBytes"]}, "Native capture proof bytes changed", "IDENTITY")
|
|
856
|
+
require(type(report.get("cells")) is list and 0 < len(report["cells"]) <= 8, "Invalid conformance cell inventory")
|
|
857
|
+
absolute, relative = number(report.get("absoluteTolerance")), number(report.get("relativeTolerance"))
|
|
858
|
+
require(0 < absolute <= 0.01 and 0 < relative <= 0.01, "Conformance tolerance is not admitted")
|
|
859
|
+
for cell in report["cells"]:
|
|
860
|
+
operation = cell.get("operation", {})
|
|
861
|
+
require(operation.get("operation") == "NEURON_ADD" and operation.get("units") == "raw" and operation.get("tokenScope") == {"kind": "all"} and
|
|
862
|
+
operation.get("siteId") in self.sites and self.sites[operation["siteId"]]["layer"] == cell.get("layer") and
|
|
863
|
+
cell.get("validationPassed") is True and cell.get("coordinateTolerancePassed") is True and
|
|
864
|
+
number(cell.get("priorMaxAbsError")) <= absolute and number(cell.get("restorationMaxAbsError")) <= absolute,
|
|
865
|
+
"Conformance cell is unvalidated or outside the loaded tensor map", "IDENTITY")
|
|
866
|
+
integer(operation.get("neuron"), 0, self.sites[operation["siteId"]]["width"] - 1)
|
|
867
|
+
require(type(cell.get("tokenIds")) is list and 0 < len(cell["tokenIds"]) <= self.limits["maxInputTokens"], "Conformance cell token count is invalid", "IDENTITY")
|
|
868
|
+
for token in cell["tokenIds"]: integer(token, 0, 4294967295)
|
|
869
|
+
require(number(operation.get("amount")) != 0 and number(cell.get("vectorNorm")) > 0 and
|
|
870
|
+
0 <= number(cell.get("deltaMaxAbsError")) and 0 <= number(cell.get("deltaMaxRelativeL2Error")) and
|
|
871
|
+
cell.get("decodedPositions") == list(range(len(cell["tokenIds"]))), "Conformance cell lacks actual position coverage", "IDENTITY")
|
|
872
|
+
require(integer(report.get("inputTokens"), 1) == 3 * sum(len(cell["tokenIds"]) for cell in report["cells"]), "Conformance prefill accounting differs from observed positions", "IDENTITY")
|
|
873
|
+
for cell in report["cells"]: self.validated_cells[self.cell_key(cell["operation"])] = report["validationId"]
|
|
874
|
+
return {"accepted": True, "validationId": report["validationId"], "evidenceDigest": reference["sha256"], "cells": len(report["cells"]), "sampledTokens": 0}
|
|
875
|
+
|
|
876
|
+
def install(self, recipe, validating=False):
|
|
877
|
+
if recipe is None:
|
|
878
|
+
return {}, None, []
|
|
879
|
+
require(recipe.get("schema") == "omnius.nol.recipe.v1" and recipe["modelDigest"] == self.manifest["modelDigest"] and recipe["architectureMapDigest"] == self.manifest["architectureMapDigest"], "Recipe differs from resident model", "IDENTITY")
|
|
880
|
+
engine, weights = self.session.engine, self.session.weights
|
|
881
|
+
require(self.session.meta.arch in ("llama", "qwen2", "qwen3", "qwen3next", "qwen35"), "GNE neuron lowering is unverified for this architecture", "UNSUPPORTED")
|
|
882
|
+
require(type(recipe["operations"]) is list and 0 < len(recipe["operations"]) <= 1000, "Invalid operation inventory")
|
|
883
|
+
vectors, gains, actual, occupied, identifiers = {}, [], [], set(), set()
|
|
884
|
+
working, arithmetic, gain_bytes = 0, 0, 0
|
|
885
|
+
for op in recipe["operations"]:
|
|
886
|
+
kind = op.get("operation")
|
|
887
|
+
fields(op, ("id", "operation", "siteId", "tokenScope", "neuron", "amount", "units") if kind == "NEURON_ADD" else ("id", "operation", "siteId", "tokenScope", "neuron", "factor"), ("calibrationId",) if kind == "NEURON_ADD" else ())
|
|
888
|
+
require(kind in RUNTIME_OPS and op["tokenScope"] == {"kind": "all"}, "Only all-token dense neuron add/gain is supported", "UNSUPPORTED")
|
|
889
|
+
site = self.sites.get(op["siteId"])
|
|
890
|
+
require(site is not None and op["id"] not in identifiers, "Unknown site or duplicate operation identity")
|
|
891
|
+
layer, neuron = site["layer"], integer(op["neuron"], 0, site["width"] - 1)
|
|
892
|
+
require((layer, neuron) not in occupied, "Overlapping ordered operations require a separate exact lowering", "UNSUPPORTED")
|
|
893
|
+
occupied.add((layer, neuron)); identifiers.add(op["id"])
|
|
894
|
+
require(not weights.is_moe(layer) and weights.has_tensor(f"blk.{layer}.ffn_gate.weight") and weights.has_tensor(f"blk.{layer}.ffn_up.weight") and weights.has_tensor(f"blk.{layer}.ffn_down.weight"), "Only verified separate dense SwiGLU tensors are supported", "UNSUPPORTED")
|
|
895
|
+
matrix = engine.n_embd * site["width"] * 4
|
|
896
|
+
working = max(working, matrix * 4 + gain_bytes + (len(vectors) + 2) * engine.n_embd * 4)
|
|
897
|
+
arithmetic += engine.n_embd * site["width"]
|
|
898
|
+
require(working <= self.limits["maxWorkingBytes"] and arithmetic <= self.limits["maxMultiplyAdds"], "Native dequantization working/arithmetic budget exceeded", "CAPACITY")
|
|
899
|
+
weights._cache.clear()
|
|
900
|
+
if kind == "NEURON_ADD":
|
|
901
|
+
require(validating or self.cell_key(op) in self.validated_cells, "Raw neuron-add cell requires explicit native conformance proof before generation", "UNSUPPORTED")
|
|
902
|
+
require(layer > 0 and not self.session.meta.has_post_ffn_norm, "Control-vector lowering cannot implement layer0 or post-FFN normalized neuron add exactly", "UNSUPPORTED")
|
|
903
|
+
require(op["units"] in ("raw", "residual_norm"), "Activation-standard-deviation calibration is not implemented", "UNSUPPORTED")
|
|
904
|
+
stats = self.calibration(recipe, op, layer) if op["units"] == "residual_norm" else None
|
|
905
|
+
require(stats is not None or "calibrationId" not in op, "Raw operands must not carry a non-applied calibration", "UNSUPPORTED")
|
|
906
|
+
unit = self.Unit(layer, neuron, number(op["amount"]))
|
|
907
|
+
native = self.Recipe([unit], self.session.meta.model_id, "rel" if stats else "raw", when="all")
|
|
908
|
+
# No Session.vectors()/stats_view(auto=True): never synthesize
|
|
909
|
+
# calibration from the upstream default corpus during a trial.
|
|
910
|
+
vector = self.recipe_vectors(weights, stats, native)[layer]
|
|
911
|
+
require(all(math.isfinite(float(value)) for value in vector), "Nonfinite native vector")
|
|
912
|
+
vectors[layer] = vectors[layer] + vector if layer in vectors else vector
|
|
913
|
+
implementation = "gne:residual-control-vector"
|
|
914
|
+
detail = {"vectorNorm": math.sqrt(sum(float(value) ** 2 for value in vector)), "units": op["units"]}
|
|
915
|
+
else:
|
|
916
|
+
factor = number(op["factor"])
|
|
917
|
+
gains.append(self.Unit(layer, neuron, 0.0, mode="gain", k=factor))
|
|
918
|
+
gain_bytes += 4 * (engine.n_embd + site["width"])
|
|
919
|
+
require(gain_bytes + 65536 <= self.limits["maxTensorBytes"], "Native gain adapter exceeds the tensor byte bound", "CAPACITY")
|
|
920
|
+
implementation, detail = "gne:ffn-up-lora", {"factor": factor, "target": f"blk.{layer}.ffn_up.weight"}
|
|
921
|
+
validation_id = self.validated_cells.get(self.cell_key(op)) if kind == "NEURON_ADD" else None
|
|
922
|
+
actual.append({"operationId": op["id"], "operation": kind, "siteId": op["siteId"], "tokenScope": op["tokenScope"], "implementation": implementation,
|
|
923
|
+
"equivalence": "validated_equivalent" if validation_id else "unvalidated", **({"nativeValidationId": validation_id} if validation_id else {}), **detail})
|
|
924
|
+
lora = None
|
|
925
|
+
if gains:
|
|
926
|
+
require(working + gain_bytes <= self.limits["maxWorkingBytes"], "Native gain construction exceeds the working byte bound", "CAPACITY")
|
|
927
|
+
path = Path(self.temp.name) / "trial-gain.lora.gguf"
|
|
928
|
+
self.created_loras.append(str(path))
|
|
929
|
+
self.export_gain_lora(weights, self.Recipe(gains, self.session.meta.model_id, "raw", when="all"), path)
|
|
930
|
+
actual_file = hash_file(path, self.limits["maxTensorBytes"])
|
|
931
|
+
for item in actual:
|
|
932
|
+
if item["operation"] == "NEURON_GAIN": item["adapter"] = actual_file
|
|
933
|
+
lora = [(str(path), 1.0)]
|
|
934
|
+
weights._cache.clear()
|
|
935
|
+
return vectors, lora, actual
|
|
936
|
+
|
|
937
|
+
def generate(self, payload):
|
|
938
|
+
self.ready()
|
|
939
|
+
fields(payload, ("messages", "recipe", "recipeIdentityJson", "cacheKeyDigest", "seed", "maxTokens", "decoding"))
|
|
940
|
+
maximum = integer(payload["maxTokens"], 1, self.limits["maxOutputTokens"])
|
|
941
|
+
seed = integer(payload["seed"], 0, 4294967295)
|
|
942
|
+
require(SHA.fullmatch(payload["cacheKeyDigest"]), "Invalid cold cache identity")
|
|
943
|
+
decoding = payload["decoding"]
|
|
944
|
+
fields(decoding, ("temperature", "topP", "topK", "constrainedDecoding"))
|
|
945
|
+
temperature, top_p, top_k = number(decoding["temperature"]), number(decoding["topP"]), integer(decoding["topK"])
|
|
946
|
+
require(0 <= temperature <= 5 and 0 < top_p <= 1 and decoding["constrainedDecoding"] == "none", "Unsupported decoding configuration", "UNSUPPORTED")
|
|
947
|
+
prompt = self.tokenize({"messages": payload["messages"]})["tokenIds"]
|
|
948
|
+
require(len(prompt) + maximum <= self.binding["contextLimit"], "Physical context limit exceeded", "CAPACITY")
|
|
949
|
+
if payload["recipe"] is not None:
|
|
950
|
+
recipe = payload["recipe"]
|
|
951
|
+
verify_identity(payload["recipeIdentityJson"], {key: value for key, value in recipe.items() if key != "recipeDigest"}, recipe["recipeDigest"])
|
|
952
|
+
else:
|
|
953
|
+
require(payload["recipeIdentityJson"] is None, "Baseline cannot carry a recipe identity")
|
|
954
|
+
require(self.last_reset is not None and not self.created_loras, "Explicit host reset required before native generation", "RESET")
|
|
955
|
+
before, engine = self.last_reset, self.session.engine
|
|
956
|
+
ctx = engine.steer_ctx()
|
|
957
|
+
observed, original_decode = set(), engine._decode
|
|
958
|
+
def decode(context, items):
|
|
959
|
+
result = original_decode(context, items)
|
|
960
|
+
observed.update(item[1] for item in items if item[2] == 0)
|
|
961
|
+
return result
|
|
962
|
+
try:
|
|
963
|
+
vectors, lora, actual = self.install(payload["recipe"])
|
|
964
|
+
engine.set_lora(ctx, lora)
|
|
965
|
+
engine.set_cvec(ctx, vectors or None)
|
|
966
|
+
engine._decode = decode
|
|
967
|
+
prefilled = engine.prefill(ctx, [prompt])
|
|
968
|
+
sampling = self.Sampling(temperature=temperature, top_p=top_p, top_k=top_k, min_p=0, presence_penalty=0, seed=seed, dry_multiplier=0)
|
|
969
|
+
rollout = engine.generate_greedy(ctx, [prompt], max_tokens=maximum, top_k=min(5, engine.n_vocab), prefilled=prefilled, sampling=sampling)[0]
|
|
970
|
+
require(len(rollout.token_ids) <= maximum and len(rollout.text.encode()) < MAX_FRAME // 2, "Native output exceeds its bound", "CAPACITY")
|
|
971
|
+
positions = {item["operationId"]: sorted(observed) for item in actual}
|
|
972
|
+
engine._decode = original_decode
|
|
973
|
+
reset = self.reset()
|
|
974
|
+
return {"text": rollout.text, "promptTokenIds": prompt, "tokenIds": rollout.token_ids,
|
|
975
|
+
"usage": {"promptTokens": len(prompt), "completionTokens": len(rollout.token_ids)}, "finishReason": "stop" if rollout.finish == "eog" else "length",
|
|
976
|
+
"native": {"binding": self.binding, "implementation": WORKER_VERSION, "operations": actual, "editedPositions": positions,
|
|
977
|
+
"cacheKeyDigest": payload["cacheKeyDigest"], "resetBefore": before, "resetAfter": reset, "usesCache": True, "cacheScope": "within_trial_only",
|
|
978
|
+
"recipeDigest": payload["recipe"]["recipeDigest"] if payload["recipe"] else None}}
|
|
979
|
+
except BaseException:
|
|
980
|
+
engine._decode = original_decode
|
|
981
|
+
try: self.reset()
|
|
982
|
+
except BaseException as error: raise Rejected("RESET", "Native GNE state could not be restored", True) from error
|
|
983
|
+
raise
|
|
984
|
+
|
|
985
|
+
def close(self):
|
|
986
|
+
try:
|
|
987
|
+
if self.session is not None:
|
|
988
|
+
self.reset()
|
|
989
|
+
self.session.close()
|
|
990
|
+
finally:
|
|
991
|
+
self.session = None
|
|
992
|
+
self.loaded = self.confirmed = False
|
|
993
|
+
self.validated_cells.clear()
|
|
994
|
+
self.runtime_build = None
|
|
995
|
+
if self.temp is not None:
|
|
996
|
+
self.temp.cleanup()
|
|
997
|
+
self.temp = None
|
|
998
|
+
return {"closed": True, "pid": os.getpid(), "allocationReleaseRequiresHostVerification": True}
|
|
999
|
+
|
|
1000
|
+
def read_exact(stream, count):
|
|
1001
|
+
data = bytearray()
|
|
1002
|
+
while len(data) < count:
|
|
1003
|
+
part = stream.read(count - len(data))
|
|
1004
|
+
if not part:
|
|
1005
|
+
require(not data, "Truncated worker frame")
|
|
1006
|
+
return None
|
|
1007
|
+
data.extend(part)
|
|
1008
|
+
return bytes(data)
|
|
1009
|
+
|
|
1010
|
+
|
|
1011
|
+
def serve():
|
|
1012
|
+
sys.stdout = sys.stderr # Native libraries and warnings cannot corrupt framing.
|
|
1013
|
+
require(0 < MAX_FRAME <= 67108864 and all(OWNER[key] for key in OWNER) and type(OWNER["generation"]) is int,
|
|
1014
|
+
"Missing private worker ownership environment")
|
|
1015
|
+
runtime, sequence = Runtime(), 0
|
|
1016
|
+
while True:
|
|
1017
|
+
header = read_exact(sys.stdin.buffer, 4)
|
|
1018
|
+
if header is None:
|
|
1019
|
+
break
|
|
1020
|
+
size = struct.unpack(">I", header)[0]
|
|
1021
|
+
require(0 < size <= MAX_FRAME, "Worker input frame exceeds byte limit", "CAPACITY")
|
|
1022
|
+
raw = read_exact(sys.stdin.buffer, size)
|
|
1023
|
+
require(raw is not None, "Truncated worker request")
|
|
1024
|
+
request = parse_json(raw.decode("utf-8", "strict"))
|
|
1025
|
+
fields(request, ("schema", "kind", "sessionId", "jobId", "ownerId", "generation", "id", "action", "payload"))
|
|
1026
|
+
require(request["schema"] == PROTOCOL and request["kind"] == "request" and
|
|
1027
|
+
all(request[key] == value for key, value in OWNER.items()) and request["id"] == sequence + 1,
|
|
1028
|
+
"Worker request ownership/sequence mismatch", "IDENTITY")
|
|
1029
|
+
sequence += 1
|
|
1030
|
+
response = {key: request[key] for key in ("schema", "sessionId", "jobId", "ownerId", "generation", "id", "action")}
|
|
1031
|
+
response["kind"] = "response"
|
|
1032
|
+
closing = False
|
|
1033
|
+
try:
|
|
1034
|
+
action, payload = request["action"], request["payload"]
|
|
1035
|
+
if action == "hello":
|
|
1036
|
+
fields(payload, ())
|
|
1037
|
+
result = {"protocol": PROTOCOL, "workerVersion": WORKER_VERSION, "pid": os.getpid(), "workerSha256": hash_file(Path(__file__).resolve())["sha256"],
|
|
1038
|
+
"pythonVersion": sys.version.split()[0], "loaded": runtime.loaded}
|
|
1039
|
+
elif action == "inspect":
|
|
1040
|
+
result = runtime.inspect(payload)
|
|
1041
|
+
elif action == "load":
|
|
1042
|
+
result = runtime.load(payload)
|
|
1043
|
+
elif action == "confirm_placement":
|
|
1044
|
+
result = runtime.confirm(payload)
|
|
1045
|
+
elif action == "tokenize":
|
|
1046
|
+
result = runtime.tokenize(payload)
|
|
1047
|
+
elif action == "reset":
|
|
1048
|
+
fields(payload, ())
|
|
1049
|
+
result = runtime.reset()
|
|
1050
|
+
elif action == "generate":
|
|
1051
|
+
result = runtime.generate(payload)
|
|
1052
|
+
elif action == "profile":
|
|
1053
|
+
result = runtime.profile(payload)
|
|
1054
|
+
elif action == "close":
|
|
1055
|
+
fields(payload, ())
|
|
1056
|
+
result, closing = runtime.close(), True
|
|
1057
|
+
else:
|
|
1058
|
+
raise Rejected("UNSUPPORTED", "Unknown worker command")
|
|
1059
|
+
response["result"] = result
|
|
1060
|
+
except Rejected as error:
|
|
1061
|
+
response["error"] = {"code": error.code, "message": str(error)[:4096], "fatal": error.fatal}
|
|
1062
|
+
closing = error.fatal
|
|
1063
|
+
except BaseException as error:
|
|
1064
|
+
# No model text, arbitrary traceback or local paths enter protocol errors.
|
|
1065
|
+
response["error"] = {"code": "RUNTIME_FAILURE", "message": type(error).__name__, "fatal": True}
|
|
1066
|
+
closing = True
|
|
1067
|
+
body = json.dumps(response, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
|
1068
|
+
require(len(body) <= MAX_FRAME, "Worker response frame exceeds byte limit", "CAPACITY")
|
|
1069
|
+
WIRE_OUT.write(struct.pack(">I", len(body)) + body)
|
|
1070
|
+
WIRE_OUT.flush()
|
|
1071
|
+
if closing:
|
|
1072
|
+
break
|
|
1073
|
+
runtime.close()
|
|
1074
|
+
|
|
1075
|
+
|
|
1076
|
+
if __name__ == "__main__":
|
|
1077
|
+
try:
|
|
1078
|
+
serve()
|
|
1079
|
+
except BaseException as error:
|
|
1080
|
+
sys.stderr.write("NOL worker retired: " + type(error).__name__ + "\n")
|
|
1081
|
+
sys.exit(1)
|